Re: when can realloc fail?
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxx>
- Date: Wed, 04 Apr 2007 08:37:38 -0400
CBFalconer wrote:
Joe Wright wrote:
... snip ...
I have posed a question a little upthread: Given ptr points to an
area to be freed, and then 'realloc(ptr, 0);'. Granted that realloc
can return NULL or not, will the allocation of ptr be freed? I'd
like to think so.
You don't know, which is one more reason to consider such
allocaters to be brain-dead.
The question isn't so much about implementations, but
about what the Standard requires/allows. In the passage
you and pete pointed out, the Standard allows realloc(p,0)
to return NULL or non-NULL at the implementation's whim.
If it returns NULL, the programmer has no way to distinguish
failure from success. (The dodge of changing zero to one is
clever, but the cure is worse than the disease: You get a
reliable success/failure indication, but at the price of
either failing unnecessarily or creating a memory leak.)
It seems to me the Standard could have defined realloc(p,0)
as equivalent to (free(p), (void*)NULL), but neither C90 nor
C99 actually chose to do so. (C90 had the free() equivalence
but didn't specify the returned value; C99 describes the
returned value but removes the free() language.)
The Rationale claims that realloc(p,0) *does* free the
memory pointed to by p, basing the claim on the deallocation
of the old object. But since the NULL return is overloaded
to mean both "failure" and "success: nothing allocated," the
programmer is stuck with a diagnostic problem.
Suggested work-around: Don't call realloc() with the second
argument equal to zero. That is, call realloc() to grow a
memory area or to shrink it, but avoid shrinking it to nothing.
If you want to free memory, use free().
--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxx
.
- References:
- when can realloc fail?
- From: banansol
- Re: when can realloc fail?
- From: santosh
- Re: when can realloc fail?
- From: banansol
- Re: when can realloc fail?
- From: santosh
- Re: when can realloc fail?
- From: Old Wolf
- Re: when can realloc fail?
- From: pete
- Re: when can realloc fail?
- From: Joe Wright
- Re: when can realloc fail?
- From: CBFalconer
- when can realloc fail?
- Prev by Date: Re: read one line of input from file and then destroying it!
- Next by Date: Re: read one line of input from file and then destroying it!
- Previous by thread: Re: when can realloc fail?
- Next by thread: Re: when can realloc fail?
- Index(es):
Relevant Pages
|