Re: xmalloc



On Sun, 24 Jun 2007 09:12:06 -0400, Eric Sosman wrote:
Already mentioned a few times in this thread:

buff = malloc(image_size);
if (buff == NULL) {
fprintf (stderr, "Image too large (%lu) to paste\n",
(unsigned long)image_size);
return;
}
/* read image into buff, insert in current document */

Here's another I think has been referred to:

must_have_mem = malloc(how_much);
if (must_have_mem == NULL) {
fprintf (stderr, "Out of memory; shutting down\n");
save_snapshot(snapshot_file);
exit (EXIT_FAILURE);
}
/* store "must have" data in allocated memory */

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.

And here's still another (I don't remember whether it's
cropped up in this thread yet):

void *getmem(size_t bytes) {
void *new = malloc(bytes);
if (new == NULL && bytes > 0) {
fprintf (stderr, "Failed to allocate %lu bytes\n",
(unsigned long)bytes);
free (emergency_stash);
emergency_stash = NULL;
new = malloc(bytes);
if (new == NULL) {
fprintf (stderr, "You were warned ...!\n");
exit (EXIT_FAILURE);
}
fprintf (stderr, "Running on fumes: save your work "
"and exit soon!\n");
}
return NULL;
}

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.

Even if out-of-memory is a "fatal error," it does not follow
that the program should have no opportunity to "die with dignity."
Have you made a will, Roland?

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)


--
Roland Pibinger
"Software development has been, is, and will remain fundamentally hard" - Grady Booch
.



Relevant Pages

  • Alsa broken pipe (example code)
    ... unsigned short int audio_format; ... exit; ... fprintf (stderr, ...
    (comp.os.linux.development.apps)
  • Re: xmalloc
    ... buff = malloc; ... fprintf (stderr, "Image too large (%lu) to paste\n", ... They pass the problem to the caller or exit the program. ...
    (comp.lang.c)
  • Re: xmalloc
    ... Roland Pibinger wrote: ... fprintf (stderr, "Image too large (%lu) to paste\n", ... exit; ...
    (comp.lang.c)
  • Re: file bug
    ... exit; ... fprintf (stderr, ... fclose; ...
    (comp.lang.c)
  • [EXPL] Microsoft ASN.1 Library Buffer Overflow Exploit
    ... The following security advisory is sent to the securiteam mailing list, and can be found at the SecuriTeam web site: http://www.securiteam.com ... GNU General Public License for more details. ... fprintf(stderr, "gethostbyname(%s) failed\n", argv); ...
    (Securiteam)