What is the difference between xmalloc()
and malloc()
for memory allocation?
Is there any pro of using xmalloc()
?
an primitive example of xmalloc.c in K&R C
#include
extern char *malloc ();
void *
xmalloc (size)
unsigned size;
{
void *new_mem = (void *) malloc (size);
if (new_mem == NULL)
{
fprintf (stderr, "fatal: memory exhausted (xmalloc of %u bytes).\n", size);
exit (-1);
}
return new_mem;
}
then in your code header (early) you put
#define malloc(m) xmalloc(m)
to silently rewrite the source before compilation. (you can see the rewritten code by invoking the C preprocessor directly and saving the output. )
if crashing your program is not what you want you can do something different
Users don't enjoy losing their data to a built-in crash command in their program.