How can I check if there is enough heap memory available?

我怕爱的太早我们不能终老 提交于 2019-11-30 03:35:49

问题


I have an assignment that requires me to create a "Heap" class that allocates and deallocates memory. I believe that my code works and the solution builds and runs properly but I want to make sure that I am not getting any memory leaks. I also need to add some code that checks if the desired amount to be allocated to the heap is even available...if someone were to allocate a very large amount. How is it possible to check if the memory allocated on the heap is available or NULL if there is not enough memory. Here is my code so far:

#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:


It's not necessary to check beforehand, just try to allocate memory and if you can't, then catch the exception. In this case it is of type 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;
};

Important note

Be sure to guard against double-freeing memory. One way to do that would be to pass your pointer to deallocateMemory by reference, allowing the function to change the pointer value to NULL, thereby preventing the possibility of delete-ing the pointer twice.

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

This prevents problems like the following:

double *chunkNew = heap.allocateMemory(hMemory);
heap.deallocateMemory(chunkNew);
heap.deallocateMemory(chunkNew); // chunkNew has been freed twice!


来源:https://stackoverflow.com/questions/16158981/how-can-i-check-if-there-is-enough-heap-memory-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!