How can I check for sufficient heap memory?

I have a task that requires me to create a Heap class that allocates and frees memory. I believe my code works and the solution builds and works correctly, but I want to make sure that I have no memory leaks. I also need to add a code that checks if the allocated amount is available for the heap ... if someone has to allocate a very large amount. How can I check if there is memory allocated on the heap, or NULL if there is not enough memory. Here is my code:

#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;
}
+5
source share
1 answer

No need to pre-check, just try to allocate memory, and if you can’t, then catch the exception. In this case, it has a 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;
};

. - 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!
+8

All Articles