Re: xmalloc
- From: rpbg123@xxxxxxxxx (Roland Pibinger)
- Date: Sun, 24 Jun 2007 19:54:27 GMT
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
.
- Follow-Ups:
- Re: xmalloc
- From: Eric Sosman
- Re: xmalloc
- References:
- xmalloc
- From: Malcolm McLean
- Re: xmalloc
- From: Richard Heathfield
- Re: xmalloc
- From: Roland Pibinger
- Re: xmalloc
- From: Eric Sosman
- Re: xmalloc
- From: Roland Pibinger
- Re: xmalloc
- From: Eric Sosman
- xmalloc
- Prev by Date: Re: Very Simple, Minimalist Technique For OOP in C...
- Next by Date: Re: Casts
- Previous by thread: Re: xmalloc
- Next by thread: Re: xmalloc
- Index(es):
Relevant Pages
|
|