TIL emalloc() auto-exits on out-of-memory errors

submited by
Style Pass
2024-10-31 21:30:05

And today I learned that there's a family of e___() functions like emalloc() and ecalloc() which will exit the process if the malloc()-returned pointer is NULL. These functions are only present in the BSD family of operating system's util.h system header. They aren't standard C functions.

The easprintf(), efopen(), ecalloc(), emalloc(), erealloc(), ereallocarr(), estrdup(), estrndup(), estrlcat(), estrlcpy(), estrtoi(), estrtou(), and evasprintf() functions operate exactly as the corresponding functions that do not start with an e except that in case of an error, they call the installed error handler that can be configured with esetfunc().

For the string handling functions, it is an error when the destination buffer is not large enough to hold the complete string. For functions that allocate memory or open a file, it is an error when they would return a null pointer. The default error handler is err(). The function esetfunc() returns the previous error handler function. A NULL error handler will just call exit().

I just thought it was cool that this was a thing that is built into an operating system's C standard library. That's batteries included for sure.

Leave a Comment