What is the difference between xmalloc and malloc?

前端 未结 6 1180
萌比男神i
萌比男神i 2021-01-31 13:57

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

6条回答
  •  天涯浪人
    2021-01-31 14:31

    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.

提交回复
热议问题