What is the difference between xmalloc and malloc?
xmalloc()
is a non-standard function that has the motto succeed or die. If it fails to allocate memory, it will terminate your program and print an error message to stderr
.
The allocation itself is no different; only the behaviour in the case that no memory could be allocated is different.
Use malloc()
, since it's more friendly and standard.
xmalloc
is not part of the standard library. It's usually the name of a very harmful function for lazy programmers that's common in lots of GNU software, which calls abort
if malloc
fails. Depending on the program/library, it might also convert malloc(0)
into malloc(1)
to ensure that xmalloc(0)
returns a unique pointer.
In any case, abort
ing on malloc
failure is very very bad behavior, especially for library code. One of the most infamous examples is GMP (the GNU multiprecision arithmetic library), which aborts the calling program whenever it runs out of memory for a computation.
Correct library-level code should always handle allocation failures by backing out whatever partially-completed operation it was in the middle of and returning an error code to the caller. The calling program can then decide what to do, which will likely involve saving critical data.
As others have mentioned, it's true that xmalloc
is very often implemented as a wrapper function that invokes the OS-supplied malloc
and blindly calls abort
or exit
if it fails. However, many projects contain an xmalloc
function that tries to save application state before exiting (see, for example, neovim).
Personally, I think of xmalloc
as a kind of project-specific extended malloc
rather than an exiting malloc
. Though I don't recall ever seeing a version that didn't wind up calling abort
or exit
, some of them do a lot more than that.
So the answer to the question "What's the difference between xmalloc
and malloc
is: it depends. xmalloc
is a non-standard, project-specific function, so it could do anything at all. The only way to know for sure is to read the code.