Mail Archives: djgpp/1999/12/22/09:50:44
Damian Yerrick wrote:
>
> "Eric Sosman" <eric DOT sosman AT east DOT sun DOT com> wrote in message
> news:385FE52F DOT E2F5572B AT east DOT sun DOT com...
> > Damian Yerrick wrote:
> > > [...]
> > > Oh, by the way, does anyone know what the standard
> > > says should happen when you free(NULL)?
> >
> > "If _ptr_ is a null pointer, no action occurs."
>
> Simplifies things a bit.
>
> #define Free(ptr) free(ptr); ptr = NULL
This is a poor idea on two counts. First, the macro
expansion is faulty and will fail badly in situations like
if (throw_it_away)
Free(ptr);
or (harder to fix)
Type **ptr;
...
Free (*ptr++);
The second drawback is that NULLing a free'd pointer may
give an illusion of security which is completely false. If it
is to be effective, `ptr' must be the one and only copy of the
free'd pointer value anywhere in the program; setting `ptr' to
NULL will not affect any other now-invalid copies which may
reside elsewhere. Note, for example, that if `ptr' is a
function argument, the proposed Free() macro (in a corrected
version) would only change the function's local copy, not the
original in the function's caller.
It is much better -- in fact, it is essential -- to use
proper discipline in managing dynamic memory. Write your
programs so that the responsibility for acquiring and releasing
memory (and other resources, for that matter) is well controlled,
and don't count on unreliable tricks to cover up carelessness.
--
Eric Sosman
esosman AT acm DOT org
- Raw text -