In this article we will discuss how to Handle Out of Memory errors in a C++ Application.

Each process has a limited free storage or heap associated with it for dynamic memory allocation. If application consumes all the memory from heap then process will crash with out of memory error.

Check out following example, here we are allocation memory on heap in continous loop without deleting that memory. After it consumes all the memory programm will crash.

 

Imp Point:

Build this program in 32 Bit because in 32 Bit Application process’s size is 4GB maximum i.e. 2^32, where as in 64 Bit Application memory limit is 2^64 and thats impractical to reach. So, if you will run 64 Bit version of this program then it will take a lot of time to crash.

Command to build 32 Bit version in 64 Bit OS,

g++ -m32 main.cpp

 

With above code process will crash because when all the memory from heap is consumed and new or new[] fails to allocate the memory then new/new[] through an exception i.e. std::badalloc.
If your application is not catching this exception then it will crash.

How to handle out of memory crashes by catching exceptions

As new and new[] throws std::badalloc execption, so let’s catch that.

Modifications in above example are as follows,

Imp Point: Header <new> is required for std::badalloc.

What if you want to call a special function if out of memory happens.

In this special function do any thing like,

  • Make memory available again by deleting some of the memory from heap.
  • Do some application specific logging.
  • Start another instance of the application as a seperate process, so that services it provides can be continous.
  • etc.

Let’s see how to call this custom function in case of out of memory,

In case new and new[] functons are not able to allocate memory on heap they call a special function i.e. new-handler. Its a function pointer and you can set your application’s function as new-handler. If and only if this new handler function is sucessful in makeing some memory avialable then only it should return other wise it should exit the application else your application will enter a never ending cycle i.e.

operator new —> new_handler()—->operator new —> new_handler()—->……….

Check out this example,

Thanks.