E
Eric Sosman
I think you have a serious misunderstanding here. realloc does not always
call free, for example if it is passed a smaller size to reallocate. It
is nice to be able to pass NULL to realloc to get extra functionality,
with free there is no new functionality from passing NULL.
realloc() need not actually call free(), of course. However,
it must occasionally do the same thing free() does: De-allocate a
formerly-allocated region and make it available for re-allocation.
I've shown a scenario in which it is convenient for realloc() to
operate with a NULL first argument (that is, "de-allocate" the
non-existent old region). Since it's doing "the same thing" as
free(), things are more consistent if we can say "When realloc()
cannot readjust the old region in place, it allocates a new region,
copies the relevant data, and treats the old region `as if by' free()."
Also, some realloc() implementations will *always* move the region,
even when shrinking it or when there happens to be a "gap" right after
it. And then they'll fill the old region with 0xDEADBEEF or some such.
Can you guess why a realloc() implementor would choose to do this?
I don't see why at all.
You may not have used many implementations then. Maybe the division is
getting optimized out - try volatile. For example on gcc
main()
{
volatile a=0;
a=1/a;
}
Running this on Linux produces,
Floating point exception
"He sees, but he does not observe." -- S. Holmes
Ponder this, Sandeep: How did the computer know it should emit
a "Floating point exception" message? What prompted it do do so?
Is this just something computers do every now and again, when the
whim strikes them?[*] Funny coincidence that the whim happened to
strike just at the moment when a zero division was attempted,
don't you think?
Or, hey, wait: Maybe a check was made? Naaah, too obvious ...
[*] Sometimes it seems that way, doesn't it? But somehow there
always turns out to be some other excuse for their whimsical behavior.
Computers are liberally endowed with what my grandfather called "the
innate animosity of inanimate objects," but you'll never get them to
actually admit how much they enjoy messing with our minds.
What would you think of passing a NULL pointer to strlen or fclose? Even
if you can get away with it in the case of free, it is sloppy programming.
What would you think of passing a null pointer to fflush()?
Or to system()? Or to tmpnam(), or as the second argument to
setlocale(), or as the first argument to strtok(), or as the
first argument to freopen(), or as an operand of ==, or ...?
All of these functions have well-defined behaviors when the
argument/operand is a null pointer. So does free().