Roland said:
The above approachs do not handle OOM ('handle' in the meaning of
'remedy'). They pass the problem to the caller or exit the program.
The second approach would soon be refactored into a malloc_or_exit()
function.
Where did "remedy" creep into the picture? Both of the
above sketches acknowledge that the program is unable to
carry out some operation in the absence of sufficient memory,
but both "handle" the lack by taking a substitute action.
The first might be found in something like an interactive
editor, where the user gets a chance to say "Forty gig? Oh,
right, that's the original super-high-resolution file, not
the low-res image I actually intended to use." The second
does something that seems to have escaped your notice, to
wit, it calls save_snapshot() to preserve the valuable state
before pulling the plug. Neither strategy could be implemented
if malloc() just decided to blow up the program on its own whim.
This actually is an attempt to cope with OOM. But, as demonstrated,
the possibilities are very limited. You cannot do much when the
primary source of your program is exhausted.
How much you can do depends on how much you have made
provision for. That in turn depends on your analysis of how
much memory the program requires for "last gasp" operations.
At a PPOE this feature of the program received regular Q/A:
a whole bunch of state was loaded into memory, and then the
test harness induced artificial malloc failures; if the
program's emergency stash wasn't enough to sustain the last
gasp, a bug got filed.
I consider to use
void *xmalloc (size_t bytes) {
return getmem (bytes);
}
which, IMHO, elegently combines the best of all approaches posted so
far in this thread ;-)
In general I prefer: 'Repair what you can — but when you must fail,
fail noisily and as soon as possible'
(
http://www.catb.org/~esr/writings/taoup/html/ch01s06.html#id2878538)
"When you must fail" is not blanket advice to give up
the ghost at the first sign of adversity. You might also
note that all three of the sketches I provided made noise.