10

我有一个任务要求我创建一个分配和释放内存的“堆”类。我相信我的代码可以正常工作并且解决方案可以正常构建和运行,但我想确保我没有遇到任何内存泄漏。我还需要添加一些代码来检查分配给堆的所需数量是否可用......如果有人要分配非常大的数量。如果没有足够的内存,如何检查堆上分配的内存是否可用或 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;
}
4

1 回答 1

12

无需事先检查,只需尝试分配内存,如果不能,则捕获异常。在这种情况下,它是类型bad_alloc

#include <iostream>
#include <new>      // included for std::bad_alloc

/**
 * Allocates memory of size memorySize and returns pointer to it, or NULL if not enough memory.
 */
double* allocateMemory(int memorySize)
{
  double* tReturn = NULL;

  try
  {
     tReturn = new double[memorySize];
  }
  catch (bad_alloc& badAlloc)
  {
    cerr << "bad_alloc caught, not enough memory: " << badAlloc.what() << endl;
  }

  return tReturn;
};

重要的提示

一定要防止双重释放内存。一种方法是通过引用传递你的指针deallocateMemory,允许函数将指针值更改为,从而防止 -指针两次NULL的可能性。delete

void deallocateMemory(double* &dMemorySize)
{
   delete[] dMemorySize;
   dMemorySize = NULL; // Make sure memory doesn't point to anything.
};

这可以防止出现以下问题:

double *chunkNew = heap.allocateMemory(hMemory);
heap.deallocateMemory(chunkNew);
heap.deallocateMemory(chunkNew); // chunkNew has been freed twice!
于 2013-04-23T00:35:36.233 回答