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

前端 未结 1 1136
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 17:03

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 proper

1条回答
  •  时光取名叫无心
    2021-01-04 17:47

    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 
    #include       // 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!
    

    0 讨论(0)
提交回复
热议问题