Handling storage allocation failure in C
One of the issues when programming in C is to choose a strategy for dealing with allocation failures, e.g., what to do when malloc returns 0? One approach, perhaps one that is all too common, is to simply ignore the possibility of failure. This works (and avoids a lot of code writing) if the occasional strange crash isn't important. A more responsible strategy is to check each malloc return for validity and write error response code in each case.
Writing "check for errors and writing response code" for each call to malloc is, of course, a viable strategy. However there are issues to be considered. Three such are (a) the unreliability of "fixup" code, (b) the non-uniformity of error response, and (c) code littering.
But what, the skeptic says, should we do when we want to do something special such as retrying with a smaller size or using an alternative less memory intensive algorithm? One answer is simple and obvious; don't use the wrapper in these special cases. A better answer is to have a second entry into the wrapper package that does return 0 on a failure to allocate, the point being that the wrapper can have a back door to force failure, a feature very useful in a test harness. We all test our code in test harnesses, don't we?
Some have argued that a wrapper that terminates the program when there is an error is a "crash and burn" strategy that can lead to a large loss of results, i.e., losing files, data, or calculations. This is pretty much of a strawman. Programs can crash at any time for reasons beyond the control of the program; if preserving results is critical, there are well known strategies such as checkpointing and journaling. More than that using wrappers and an error management package is not a "crash and burn" strategy, it is a "black box" strategy, i.e., a strategy that is oriented towards preserving critical information when there is a crash.
This page was last updated March 1, 2008.