我有一个任务要求我创建一个分配和释放内存的“堆”类。我相信我的代码可以正常工作并且解决方案可以正常构建和运行,但我想确保我没有遇到任何内存泄漏。我还需要添加一些代码来检查分配给堆的所需数量是否可用......如果有人要分配非常大的数量。如果没有足够的内存,如何检查堆上分配的内存是否可用或 NULL。到目前为止,这是我的代码:
#include <iostream>
using namespace std;
class Heap{
public:
double* allocateMemory(int memorySize)
{
return new double[memorySize];
};
void deallocateMemory(double* dMemorySize)
{
delete[] dMemorySize;
};
};
int main()
{
Heap heap;
cout << "Enter the number of double elements that you want to allocate: " << endl;
int hMemory;
const int doubleByteSize = 8;
cin >> hMemory;
double *chunkNew = heap.allocateMemory(hMemory);
cout << "The amount of space you took up on the heap is: " <<
hMemory*doubleByteSize << " bytes" <<
starting at address: " << "\n" << &hMemory << endl;
heap.deallocateMemory(chunkNew);
system("pause");
return 0;
}