Roland said:
Not all resources are equal and need equal treatment. It hardly makes
sense to check the return value of malloc. Just use a xmalloc function
which can be found in many variants on the internet (e.g.
http://www.tug.org/tex-archive/dviware/dvi2xx/xmalloc.c).
Besides the objections from the other posters here, this code is
seriously inflexible. You *may* want to ignore the error, or you may
wish to deal with it at the callsite, or maybe you just want assistance
with debugging. But probably, you want some combination of those
three. It pays to make your solution more powerful. For example:
====== ymalloc.h ==============================
/* Just use ymalloc in place of malloc */
#define ymalloc(sz) betterMallocInternal (sz, __FILE__, __LINE__);
extern void * betterMallocInternal (size_t sz, const char * file, int
line);
/* The possible kinds of failures we detect */
enum mallocErrs { MALLOC_ERR_ZERO = 0, MALLOC_ERR_NO_MEM = 1 };
/* Settable error handler for ymalloc (might not be thread safe.) */
extern void (* mallocLogFail) (enum mallocErrs errkind, const char *
file, int line, size_t sz);
====== ymalloc.c ==============================
#include <stdlib.h>
static void logFail (enum mallocErrs errkind, const char * file, int
line, size_t sz) {
char * msgs[2] = { "", "Out of memory; " };
fprintf (stderr, "fatal: %smalloc of %lu bytes at %s[%d].\n",
msgs[errkind], (unsigned long) sz, file, line);
exit (EXIT_FAILURE);
}
void (* mallocLogFail) (enum mallocErrs errkind, const char * file, int
line, size_t sz) = logFail;
void * betterMallocInternal (size_t sz, const char * file, int line) {
void * ptr;
if (!sz) {
mallocLogFail (MALLOC_ERR_ZERO, file, line, sz);
return NULL;
}
if (NULL == (ptr = malloc (sz))) {
mallocLogFail (MALLOC_ERR_NO_MEM, file, line, sz);
}
return ptr;
}
===============================================
The point is that you can choose the policy about what to do about the
failing malloc on a scenario by scenario basis. Malloc() is a slow
enough function, that adding in any arbitrary amount of structure,
debugging, analysis etc, is usually well worth it for the relative
cost.