如何检查是否有足够的堆内存可用?

时间:2013-04-23 00:32:21

标签: c++ visual-c++ heap-memory

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

1 个答案:

答案 0 :(得分:11)

没有必要事先检查,只是尝试分配内存,如果不能,则捕获异常。在这种情况下,它的类型为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!