Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between xmalloc and malloc?

Tags:

c

What is the difference between xmalloc() and malloc() for memory allocation?
Is there any pro of using xmalloc()?

like image 412
vaichidrewar Avatar asked Sep 28 '11 22:09

vaichidrewar


2 Answers

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.

like image 107
orlp Avatar answered Oct 06 '22 18:10

orlp


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, aborting 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.

like image 31
R.. GitHub STOP HELPING ICE Avatar answered Oct 06 '22 16:10

R.. GitHub STOP HELPING ICE