Handling Out Of Memory Errors in Code

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.

#include<iostream>

int main()
{
    // Keep allocating memory dynamically on heap
    // in a cycle till new throws an exception
    // and application crashes
    while(true)
    {
        int * ptr = new int[1000];
    }

    return 0;
}

 

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

[showads ad=inside_post]

 

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,

#include<iostream>
#include<new>

int main()
{
    try
    {
        // Keep allocating memory dynamically on heap
        // in a cycle till new throws an exception
        while(true)
        {
            int * ptr = new int[1000];
        }
    }
    catch (std::bad_alloc& excepObj)
    {
        std::cout << "bad_alloc Exception :: OUt Of Memory " << excepObj.what() << '\n';
    }
    return 0;
}

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,

#include <iostream>
#include <cstdlib>
#include <new>


void out_of_memory()
{
    std::cout<<"Out of Memory :: Handler \n";

    // If not able to make memory available then exit else return.
    std::exit (1);

}

int main()
{
    // Set new handler
    std::set_new_handler(out_of_memory);
    
    // Keep allocating memory dynamically on heap
    // in a cycle till new throws an exception and before 
    // that calls the registered new_handler
    while(true)
    {
        int * ptr = new int[1000];
    }

    return 0;
}

Thanks.

1 thought on “Handling Out Of Memory Errors in Code”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top