What should I do if malloc() fails?

May 14, 2009 at 8:55pm
I was wondering what I am supposed to do if malloc() returns NULL. Currently the program shows an error message to the user, and stops with whatever it was doing at the moment. So far I have never seen the error message. But I was wondering, when there is not enough free memory, will the computer be able to show the error message anyway? I guess a Windows error message uses some memory to store information about caption, text, buttons and user interaction. Is it useful to try to show an error message?

Another question, is the number of blocks of memory allocated by malloc() limited? In my program, I am allocating thousands of small objects (about 100 bytes each), is this a problem?
Last edited on May 14, 2009 at 8:56pm
May 14, 2009 at 8:58pm
In my experience, memory allocation doesn't fail nicely. Once no more memory can be allocated, the OS simply crashes the program.
Last edited on May 14, 2009 at 8:59pm
May 14, 2009 at 11:02pm
You should still code against it and endeavor to do a graceful shutdown.
May 14, 2009 at 11:03pm
You should be able to malloc millions of small object if you have the memory.

Best thing to do is throw a std::bad_alloc exception with a static error message which gets caught & displayed in main(). Hopefully your destructors do enough cleanup freeing memory that the error processing in main does not fail.

If you use a reasonable OS and programming style, an OOM condition is recoverable.
May 16, 2009 at 4:10pm
In my experience (UNIX) it is MOST important to handle malloc failures robustly immediately following a network administrators boast that the "new sserver you wanted is already out there and ready to go". To which a typical reply is something like: "Wow, that was fast, thanks". Its at THIS point that malloc will return a NULL :))
Topic archived. No new replies allowed.