What is the difference between xmalloc()
and malloc()
for memory allocation?
Is there any pro of using xmalloc()
?
xmalloc
is part of libiberty
https://gcc.gnu.org/onlinedocs/libiberty/index.html which is a GNU utils library.
malloc
is ANSI C.
xmalloc
is often included in-source in many important GNU projects, including GCC and Binutils, both of which use it a lot. But it is also possible to build it as a dynamic library to use in your programs. E.g. Ubuntu has the libiberty-dev
package.
xmalloc
is documented at: https://gcc.gnu.org/onlinedocs/libiberty/Functions.html and on GCC 5.2.0 it is implemented on libiberty/xmalloc.c
PTR
xmalloc (size_t size)
{
PTR newmem;
if (size == 0)
size = 1;
newmem = malloc (size);
if (!newmem)
xmalloc_failed (size);
return (newmem);
}
void
xmalloc_failed (size_t size)
{
#ifdef HAVE_SBRK
extern char **environ;
size_t allocated;
if (first_break != NULL)
allocated = (char *) sbrk (0) - first_break;
else
allocated = (char *) sbrk (0) - (char *) &environ;
fprintf (stderr,
"\n%s%sout of memory allocating %lu bytes after a total of %lu bytes\n",
name, *name ? ": " : "",
(unsigned long) size, (unsigned long) allocated);
#else /* HAVE_SBRK */
fprintf (stderr,
"\n%s%sout of memory allocating %lu bytes\n",
name, *name ? ": " : "",
(unsigned long) size);
#endif /* HAVE_SBRK */
xexit (1);
}
/* This variable is set by xatexit if it is called. This way, xmalloc
doesn't drag xatexit into the link. */
void (*_xexit_cleanup) (void);
void
xexit (int code)
{
if (_xexit_cleanup != NULL)
(*_xexit_cleanup) ();
exit (code);
}
Which as others mentioned, is pretty straightforward:
malloc
exit