Richard Heathfield posted:
Yes, I can. It was evident from looking at the code that it was stupid.
Even the author wasn't sure it was correctly written.
You have convinced me. My main peeve against checking malloc's of small
quantities of memory is that it's tedious, and so I think "ExitiveMalloc"
would relieve a bit of stress, not to mention reduce the signal-to-noise
ratio of the code (who wants to read countless lines of error-checking?).
Taking your advice on board though with regard to pre-allocating some reserve
memory in case of emergency, I've cooked up the following. It's a quick
sample of a program which holds important user data in memory -- data which
must be preserved even when the program fails. I think the ExitiveMalloc
works quite well.
---------- FILE BEGIN: exitmal.h ----------
#include <stddef.h>
void *ExitiveMalloc(size_t);
---------- FILE END: exitmal.h ----------
---------- FILE BEGIN: exitmal.c ----------
#include <stddef.h>
#include <stdlib.h>
void *ExitiveMalloc(size_t const size)
{
void *const p = malloc(size);
if(!p) exit(EXIT_FAILURE);
return p;
}
---------- FILE END: exitmal.c ----------
---------- FILE BEGIN: core.c ----------
#include <stdlib.h>
#include "exitmal.h"
void *mem_needed_for_saving;
int backup_required = 0;
void SetupBackupSystem(void)
{
void InitiateEmergencyBackupSequence(void);
mem_needed_for_saving = ExitiveMalloc(98304U);
atexit(InitiateEmergencyBackupSequence);
}
void InitiateEmergencyBackupSequence(void)
{
if(backup_required)
{
/* Use pre-allocated memory to facilitate in saving */
}
}
int main(void)
{
SetupBackupSystem();
/* Let's pretend that this is a circuit schematic package,
and that the user is working on a document. */
/* Now let's say that TruncateAndToUppercase is called, and
that it fails to allocate 23 bytes. TruncateAndToUppercase
contains a call to ExitiveMalloc, and so "exit" is called
upon the allocation failure. */
return 0;
}
---------- FILE END: core.c ----------
If any function in the program invokes ExitiveMalloc, we still preserve our
user's precious data. What do you think?