Keith said:
I would argue that the representation of a cannot be changed by the
call to free, since a is passed by value. (It's also been argued that
a sufficiently clever implementation could modify a, but I'm not
convinced; in any case, it shouldn't matter for reasonable code.)
The problem is that the value of a, which was valid before the call,
may become a trap representation after the call (what changes isn't
the value, but the set of values that are considered trap
representations). As a result, accessing the value of a, even just to
compare it, invokes undefined behavior. (In most real-world
implementations, the effect would be harmless, but probably not
particularly useful.)
The OP's original code is fine, although a
little convoluted about the order of operations.
The value of `a' will _not_ be changed by the
compiler, the C standard, _any_ remotely conforming
implementation of `free()' or the architecture
(x86, Sparc, Power PC, etc.) the code is run under.
You can do anything you want with the value of
`a' with the following restrictions:
1. You cannot use it as a value to the `free()'
function again,
2. You cannot de-reference it.
Naturally, the above apply to the `free()'d
_pointer value_ `a' contains. If `a' is given
another valid pointer value (one way of which
is to assign the return of a successful `malloc()'
to it), then the above restrictions are removed.
I think the OP was trying to communicate (and I
may be wrong) (error checking removed for clarity) -
{
SomeType *a, *b;
a = malloc(SomeSize);
b = a;
/* Some stuff involving a & b */
/* We're done with a, free it */
free(a);
a = NULL; /* NULLify it */
/* Oh, and BTW, if `b' still pointed to
the same object as `a', NULLify it too */
if (a == b) {
b = NULL;
}
}
The above example is pretty clean, but in
complex code, it's possible `a' might be
`free()'d from more than one place. To
keep things simple, setting the pointer
NULL at each `free()' point helps in the
prevention of `free()'ing the pointer twice
(since it's perfectly legal to pass a NULL
pointer to `free()'). In the case of `b',
at the point where `a' was `free()'d, `b'
may contain another valid pointer _different_
from `a' (through the program's logic),
and thus is only set to NULL if its value
still matched `a's (because `a's is now invalid).
Stephen