Always check malloc'ed memory?

jldupont picture jldupont · Dec 21, 2009 · Viewed 15.1k times · Source

I often catch myself doing the following (in non-critical components):

some_small_struct *ptr=(some_small_struct *) malloc(sizeof(some_small_struct));
ptr->some_member= ...;

In words, I allocate dynamically memory for a small structure and I use it directly without checking the malloc'ed pointer. I understand there is always a chance that the program won't get the memory it asks for (duh!) but consider the following:

If the program can't even get some memory for a small structure off the heap, maybe there are much bigger problems looming and it doesn't matter after all.

Furthermore, what if handling the null pointer exacerbates the precarious situation even more?? (e.g. trying to log the condition calls even more non-existing resources etc.)

Is my reasoning sane (enough) ?

Updated:

  1. A "safe_malloc" function can be useful when debugging and might be useful otherwise
  2. +X access can hide the root cause of a NULL pointer
  3. On Linux, "optimistic memory allocation" can shadow loomin OOM (Out-Of-Memory) conditions

Answer

Nemanja Trifunovic picture Nemanja Trifunovic · Dec 21, 2009

Depends on the platform. For instance, on Linux (by default) it does not make much sense to check for NULL:

http://linux.die.net/man/3/malloc

By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer.