What is the difference between xmalloc()
and malloc()
for memory allocation?
Is there any pro of using xmalloc()
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With