Howdy,
I was reflecting recently on malloc.
Obviously, for tiny allocations like 20 bytes to strcpy a filename or
something, there's no point putting in a check on the return value of
malloc.
OTOH, if you're allocating a gigabyte for a large array, this might
fail, so you should definitely check for a NULL return.
So somewhere in between these extremes, there must be a point where you
stop ignoring malloc's return value, and start checking it.
Where do people draw this line? I guess it depends on the likely system
the program will be deployed on, but are there any good rule-of-thumbs?
The good rule of thumb is always check.
True story about an OS/2 application for fielding telephone messages:
While I was working as a subcontracor at a large corporation nearby
some 18 years ago or so, there was an OS/2 application that did
zillions of 16 byte allocations and frees. No big "gimmie a
megabyte!" demands at all. The machine had 4 MB {IIRC}, which at the
time was *cough* a lot of memory. Now, according to the statistics I
examined, the packet creation and packet deletion was at a sort of
homeostatis that should have never seen a failure. However, the
memory allocater for OS/2 had a bad habit of fragmenting memory in
some very bizarre ways if there were lots and lots of very rapid
malloc()/free() pairs. The end result is that those 16 byte
allocation requests would eventually start to fail. Since there was
no check for malloc() success in the code [I DIDN'T WRITE IT!] it
crashed heinously. My first stab at fixing it (after putting in
diagnosics to at lest describe the problem before exiting) was to call
a non-standard "CompactMemory()" routine at regular intervals. At
first, it seemed to fix the problem but it lead to to other problems.
The system had to be near real time, and the compact memory call would
freeze it up momemtarily and also, it would eventually start to fail
again anyway (even though it would run much longer before failure).
My final solution was to allocate most of available RAM into a single
block and then I wrote my own sub-allocator. It was actually very
simple because all the packets were the same size, and so I just
tagged them as free or in use with an array of bits.
So, even if you do not allocate any big memory hunks and even if you
know that all of the allocations should succeed, you should still
check them. Because things don't always behave the way that you know
that they should.
IMO-YMMV.