What is the difference between xmalloc()
and malloc()
for memory allocation?
Is there any pro of using xmalloc()
?
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.