Print ancestors of a node in a Binary Tree Node
June 13, 2012
difference between reference & pointers in C++
June 13, 2012

Out of memory condition in C++ for new operator

How will you handle a situation if new operator is not able to allocate memory on heap to your program?
In C language malloc returns NULL, if it is not able to allocate memory, so the check can be as below:

    int *ptr = malloc(sizeof(int));
    if (ptr == NULL)
        ;    // malloc not able to allocate memory on heap

The reason for not being able to allocate memory may be because there is no space in the heap or anything. So how do we check for out-of-memory conditions for new operator?
Just to mention that malloc is a function and new is an operator, however it can be overloaded as a function.

Solution:

Because of its legacy from C language, in initial versions of C++ operator new also used to return 0 (NULL). But now, Operator new handles it the C++ way. When operator new is not able to allocate memory it throws an exception, bad_alloc.
So, every time you allocate memory using operator new, you should have a try catch

    int *ptr;
    try{
        ptr = new int;
    }
    catch(std::bad_alloc&) {
        ;     // handling the case of non-allocation
    }

But writing such code every time may be a pain in a*s. :).. so what is the solution. The C language way is to use macros and handle the non-allocation case in the macro. But you know macros in C++ is suicide :).
The interesting thing is that new operator calls the client specific error-handling function before throwing the function. I can dedicate a function to handle such errors and let the compiler know about it using the set_new_handler API in new.h as shown below:

    void memallocErrorHandler()
    {
        cerr << "Unable to allocate memory";
        abort();
    }
    int main()
    {
        set_new_handler( memallocErrorHandler );
        ... ...
    }

Now if operator new is not able to allocate memory then it will call memallocErrorHandler function and it will abort the program (or does what you want it to do).

Leave a Reply

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