malloc error handling

c, malloc, memory, memory-leaks, memory-management

Solution

In C there are no exceptions (not you can use in the language anyway), so the only way `malloc` can signal failure is returning a null pointer. So you have to check the return value. If it is 0, allocation failed (for whatever reason) and no memory allocated - nothing to free; otherwise allocation for the requested amount(*) succeeded and you will have to free the memory when no longer needed.

(*) beware of overflows: `malloc` takes a `size_t` parameter, which is most likely an unsigned number. If you request `size * sizeof(int)` bytes with an unsigned `size` and the multiplication overflows (possibly an error in obtaining the value of `size`), the result is a small number. `malloc()` will allocate this small number of bytes for you returning with non-null and you index into the returned array based on the actual (large) value of `size`, possibly resulting in segmentation fault or its equivalent

Problem

What are the possible errors that can occur during memory allocation using `malloc` except `out of memory`? What are the best strategies to handle those errors? For an `out of memory exception` is it necessary to free the pointer even if memory allocation fails?

Original source