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?
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.
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 :))