Checking for the return of malloc
doesn't help you much by its own to make your allocations safer or less error prone. It can even be a trap if this is the only test that you implement.
When called with an argument of 0
the standard allows malloc
to return a sort of unique address, which is not a null pointer and which you don't have the right to access, nevertheless. So if you just test if the return is 0
but don't test the arguments to malloc
, calloc
or realloc
you might encounter a segfault much later.
This error condition (memory exhausted) is quite rare in "hosted" environments. Usually you are in trouble long before you hassle with this kind of error. (But if you are writing runtime libraries, are a kernel hacker or rocket builder this is different, and there the test makes perfect sense.)
People then tend to decorate their code with complicated captures of that error condition that span several lines, doing perror
and stuff like that, that can have an impact on the readability of the code.
I think that this "check the return of malloc
" is much overestimated, sometimes even defended quite dogmatically. Other things are much more important:
- always initialize variables, always. for pointer variables this is crucial,
let the program crash nicely before things get too bad. uninitialized pointer members in
struct
s are an important cause of errors that are difficult to find.
- always check the argument to
malloc
and Co. if this is a compile
time constant like sizof toto
there can't be a problem, but
always ensure that your vector allocation handles the zero case properly.
An easy thing to check for return of malloc
is to wrap it up with something like memset(malloc(n), 0, 1)
. This just writes a 0
in the first byte and crashes nicely if malloc
had an error or n
was 0
to start with.