Jens Gustedt's Blog

November 5, 2011

chasing a phantom: checking the return of malloc

Filed under: C99 — Jens Gustedt @ 22:46

Often you see or hear as one of the first rules that are taught about the use of malloc (and derivatives) that you’d have to check the return value, to see if it is 0 and thus to know whether it failed. Although there are situations in which malloc may fail and that this check makes sense, doing so gives you mostly false security. In most situations where this might fail you are in trouble for quite a while and the user of the program (if any) will most probably have aborted the execution since long.

Don’t understand me wrong, I don’t say you shouldn’t ever check the return of malloc, I just will try to show you that there are many other things that have to be considered before that, and that to my opinion have much more importance. They are important on systems that have very restrictive possibilities for memory allocation. Usually these are so-called freestanding environments: embedded devices, space rockets, Linux kernel, or other very specialized stuff. Programming on multi-commodity architectures (hosted environment)is quite different from that.

(more…)

Advertisements

Create a free website or blog at WordPress.com.