Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always check malloc'ed memory?

Tags:

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
like image 384
jldupont Avatar asked Dec 21 '09 17:12

jldupont


People also ask

Should I always check malloc?

Yes, however, it is required to check whether the malloc() was successful or not. Let's say malloc() failed and you are trying to access the pointer thinking memory is allocated will lead to crash, so it it better to catch the memory allocating failure before accessing the pointer.

How does malloc keep track of memory?

malloc uses an extra 8 bytes right in front of the pointer it returns to "remember" this size information. When you free said pointer, free will know both the address and read 8 bytes before the pointer to get the size info, then happily release the memory to the operating system.

How can I tell if malloc is failing?

malloc(n) returns NULL on failure. malloc(0) may return NULL . To detect failure: void* ptr = malloc(n); if (ptr == NULL && n > 0) Handle_Failure();

Does malloc use memory?

In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.


1 Answers

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.

like image 143
Nemanja Trifunovic Avatar answered Dec 23 '22 19:12

Nemanja Trifunovic