Ian said:
Consider
char* p0 = malloc(100);
char* p1 = malloc(200);
char* p2 = malloc(300);
What do you do if the second malloc throws?
You'd end up with as much if not more code for a series of try/catch
blocks as you would for a series of if() blocks.
OK, here's one idea of my own. It's not a complete solution of course.
* Allocation a big chunk of memory at the start of execution (failure here
is not critical)
* Use that as a private heap area for some allocations
* For all allocations in the application which are known to be small and
well-managed, use this private heap.
* The size of this heap is chosen to be fit comfortably all the allocations
which are likely to be active at one time.
* If this private heap overflows, while it's easy to keep expanding it, it's
better to treat this as an error in the program which uses it.
This heap allocator is not expected to fail. Therefore error returns don't
need to be checked; it will either return a valid pointer or show an error
message. (This is not that much different from expecting array indices to be
in range.)
A lot of small allocations can then make use of this instead:
char* p0 = heap(100);
char* p1 = heap(200);
char* p2 = heap(300);
....
freeheap(p0); etc..
Otherwise, if you need to use malloc() for a trivial allocation like a few
dozen bytes, then you are exposing the program to the risk of major failure;
you *must* check this allocation succeeded, and if not then you may have a
decidedly non-trivial task of cleaning up and recovering:
char *filespec;
filespec=malloc(strlen(file)+strlen(ext)+1);
if (filespec=NULL) then /* big headache of what to do about this */
....
strcopy(filespec,file);
strcat(filespec,ext);
status=checkfileexists(filespec);
free(filespec);
return status;
The fact that malloc() failed on this tiny allocation means there is a major
problem, it's not just not being able to complete this file operation (or
whatever); rather than just failing this operation, it should signal
somewhere else better able to handle this.
(And, for this function that returns 1: the file exists, 0:doesn't exist;
should a malloc() failure just return 0? That would be misleading. Perhaps
introduce 2:don't know?!)
Solution: use heap()/freeheap() instead.
(The real scenario comes from a program which is an interpreter for another
language; memory allocation/deallocation is implicit, in fact the programmer
can't even intervene:
return checkfileexists(file+ext);
The programmer may not even be aware that he narrowly missed catastrophic
failure of his application!)