【问题标题】:How can I check if there is enough heap memory available?如何检查是否有足够的堆内存可用?
【发布时间】:2013-04-16 01:20:11
【问题描述】:

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

【问题讨论】:

  • 考虑使用valgrind 来检查内存泄漏。
  • 请将 8 改为 sizeof(double)

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


【解决方案1】:

不需要事先检查,尝试分配内存,如果不能,则捕获异常。在这种情况下,它的类型是 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-ing 指针两次的可能性。

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!

【讨论】:

  • 非常感谢您的帮助!
  • 很高兴为您提供帮助。另外,自从您发表评论后,我更新了答案……有一个重要说明。
  • 其实……删除前不需要核对NULL,见stackoverflow.com/questions/615355/…
  • 我的错误,我的意思是防止另一个问题:双重释放。答案已被编辑。
猜你喜欢
  • 1970-01-01
  • 2016-03-29
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 2017-05-14
相关资源
最近更新 更多