[snip original query]
As you have seen, the general attitude is to always check, and I actually am
one of that crowd. However, I do it slightly different:
void* xmalloc(size_t s) {
void* res = malloc(s);
if(!res) {
fprintf( stderr, "malloc() failed\n");
exit(EXIT_FAILURE);
}
return res;
}
This is the basis for the approach that I take; however as Eric
notes this form is not entirely satisfactory for large programs.
The problem (in my view) lies in the error handling process.
Commonly neither the wrapper nor the using code is in any
position to make an intelligent and useful response to this kind
of resource failure. I find it better to create and use (and
reuse) a general purpose error handler that extracts state
information from the program, writes it to an error file, and
then exits gracefully.
I take the view that allocator failure is a reflection of a
program bug, commonly because there are memory leaks, there is a
size computation error, or the scale of the problem is larger
than the systems size. Such bugs are often not easily
reproducible and can occur in remote sites. I want all the
information I can get and I want it in an intelligible form.
My experience is that the combination of a portable instrumented
wrapper for allocation/deallocation and a portable error handler
that generates detailed error files works quite well and is worth
the investment up front for programs of any size.
Of course, this isn't universally true; there are environments
where a program can and even must do something intelligent about
an allocation failure and limp on.