How To Handle new Operator Failure

new operator is used to allocate memory in C++. Though it is rare that a modern day computer is not able to allocate memory for our program, still there may be situations where we have to face situations where the new operator fails. The function set_new_handler will divert the flow to a user function when the new operator fails. A simple example is given below.

#include
using namespace std;

// Function to be called when the new operator fails
void NewHandler()
{
   cout << "Out of memory" << '\n';    exit(0); }   int main() {    // Set the function to be called when new operator fails    set_new_handler(NewHandler);    while (true)    {       new int[50000000];   // Hope this will fail after a few iterations       cout << "Successful so far" << '\n';    }    return 0; } [/sourcecode] In the above example, the function NewHandler() will be called when the memory allocation using new operator fails.

Some Background Info

set_new_handler will store the function NewHandler() in a static new handler pointer. This new handler is used by operator new.

Advertisements

11 Responses to How To Handle new Operator Failure

  1. Ferruccio says:

    Another possibility is catching a bad_alloc exception. i.e:

    try
    {
    new int[5000000];
    cout << "successful so far" << endl;
    }
    catch (bad_alloc)
    {
    cout << "out of memory" << endl;
    exit(0);
    }

  2. cppkid says:

    Indeed. I just used an example to show the use of set_new_handler.
    However, I think try…catch calls are expensive in usage of resources.
    Anyway, the real advantage is that you have to define the handler function for new operator failure only once compared to the fact that you need try…catch for each block of new operators as in

    try
    {
    new int[100];
    }
    catch(…)
    {
    // Call some routine
    }
    .
    .
    .
    try
    {
    new char[100];
    }
    catch(…)
    {
    // Call some routine
    }

    Thanks for the comment. Please keep watching the blog.

  3. Brendan Leber says:

    You didn’t show how to handle new failing. What do you suggest we do if new fails? If you’re just going to exit the program it would be better to let it crash at the point of failure. That way you can zero in on the exact problem instead of trying to figure out which new statement failed.

    Why do you think exception handling is expensive? Which is more expensive handling exceptions or tracking down all of the bugs caused by objects not being deconstructed properly when the exception handler unwinds the stack?

  4. cppkid says:

    Thanks Brendan for your interest in my blog and valuable support.

    I just used an exit(0) in code as an example only (in case somebody copies the code and runs it won’t get a system hang). It is not a real life scenario , just an example I could mold out easily. I don’t think you will ever use exit(0) in this place.

    Also, I never said try…catch is a bad alternative in this situation (of course, it is something that most of the programmers, including me, prefer. I just said a general fact that try..catch calls are expensive. I just wanted to show another way to handle new operator failure. (may be my words are mis interpreted).

    And finally, what should we do if new operator fails – it is something that still I have to get a concrete idea. May be we can cause the program to wait until more memory is freed by the system when other programs exit or in the worst case, we can log it and exit. If you have some idea, please feel free to cmment it here.

    Once again, thanks for your suggestions and comments. Please keep watching the blog.

  5. Brendan Leber says:

    According to the documentation the definition of the handle function is “int __cdecl handler_func(size_t cb)”. The cb parameter contains the number of bytes that were requested by the allocation. If the handler function returns non-zero the allocation is retried, otherwise the allocation fails.

    I would do as you suggest and attempt to free some memory in the handler and return non-zero to give the system a chance to allocate the memory. If there isn’t any more memory to free then return zero and let the allocation fail. I spend a lot of time tracking down failures in systems and I recommend that you always let the system fail as close to the actual problem as possible. This allows you to quickly find the problem with tools like WinDBG.

    Now to the other subject, exception handling. Yes, exception handling creates more instructions in your executable. However, we’re talking about exceptional conditions and not the normal execution path. The gains from writing code that is maintainable far outweigh any early optimization. If you have a problem with execution speed it would be better to profile your application to find the trouble areas and only optimize them.

    These are good posts and you should keep going. I just want to give you, and your readers, food for thought.

  6. cppkid says:

    Thanks a lot Brenden…
    I expect your support in the future also….

  7. Abhrajyoti says:

    Hello Guys,
    Is anybody has idea how the try catch is actually implemented?

  8. div says:

    I have query, the requirement is i have to use 2 new operators in a single try block.If an exception occurs for 2nd new, then how do i delete the memory space allocated for 1st new.What is the best way to have the catch implementation.

  9. Santosh says:

    Hello cppkid,all ,

    I am not agree with your opinion about, this problem is not real life problem. Actually I am a developer and I am facing this problem. We have a system at our end which frequently create and delete large size arrays. we use windows 2k3 server with 4 GB ram to run the system. Our one client uses the system so heavily. IT puts load on system and our application is not able to allocate the memory to array. we cant exit our program as its huge system and there are may other task also going with he program in different threads. We just want to allocate the memory to that array any how as there is memory available in system. But new operator is not able to allocate it some how. IS there a way to delete some unnecessary memory used by program like GC and again try to allocate it.

  10. Most of these are Kind A folks. They desire an outlet, a anxiety reliever. They appear in below at six:fifteen and so they circling the place. They might wait around for getting launched. It like an appointment that they want to recover from with to allow them to get on with their day.
    http://www.tevrede.nl/indext.asp?p=26 http://www.tevrede.nl/indext.asp?p=26

  11. Johng402 says:

    Fckin amazing things here. Im very glad to see your post. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a mail? kcfgcbdkbfbe

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: