H
Herbert Rosenau
Bullshit!xmalloc() will never return null.
Now say that, on a fairly small desktop machine, we want to allocate some
tens of megabytes of memory for a large image. If the machine won't support
an allocation that size, there is no way that xmalloc() can return. It must
terminate the program. Which is almost certainly not what you want, because
it is quite forseeable that user will demand an image larger than you can
handle, and almost certainly you wnat a message such as "image requested too
large, please try a smaller one".
On the othe rhnad if a request for twenty bytes fails, we are in deep
trouble. Quite possibly the only realistic thing to do in such circumstances
is to terminate. That's what xmalloc does by default. Remember, this will
almost never happen - once in a trillion years of operation for the example
you described, under rather different assumptions, just enough for a few
users to experience it occasionally.
No. It is suitable for when custom error-handling code adds more cost than
it is worth. Which is often when allocating trivial amounts of memory in
medium-critical applications. It is not for when you have a reasonable
expectation that the memory request will be impossible to fulfil.
When you are trained in writing failsafe programs then you will act
always in failing requests of 1 byte or 100 MB allocated memory
without letting the program crash or simply exit().
When such mistake may cost lot of money, getting databases or even
simple files destroyed, leaving something in inderteminate state or
simply human live you'll catch each and any theroretical error.
Failing malloc ist one of them.
Yes, it costs carefully programming, yes, it costs a bit time to catch
each NULL from the malloc family - but you'll get a program that works
as it has to do without unexpected failture.
You does not know what to do when out of memory? It's so simple:
return the error to the caller to give it a chance to undo the action
he is in middle of and let it return to its caller to give it the
chance to undo ........ until the complete action is undone. Clean up
evering and restart the action again. As at this point the whole
system has changed the chance to get the action now complete is
realistic high.
However when you have to write failsve code you should make a complete
design of the whole project, each single action, every function and
not hack around. Really the starting point of coding will delay
significantly - but the coding phase shrinks significantly too.
--
Tschau/Bye
Herbert
Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2R Deutsch ist da!