Re: How to know the memory pointed by a ptr is freed?
From: RCollins (rcoll_at_nospam.theriver.com)
Date: Tue, 17 Aug 2004 20:24:58 -0700
Jack Klein wrote:
> On Tue, 17 Aug 2004 16:38:17 -0700, RCollins
> <firstname.lastname@example.org> wrote in comp.lang.c:
>>Which would /imply/ that free() can change the value of "ptr".
> And what about the 37 copies made of that pointer after it was
> returned from malloc() and passed to free()?
> Or what about the suitably sized array of unsigned chars into which
> the bit pattern of the pointer was copied by memcpy()?
I don't know ... the standard doesn't mention them. All I know is that
the prototype for free() doesn't _appear_ to allow the value of "ptr"
to be changed. (Ignoring the possibility of behind-the-scenes
'compiler magic'). As for those 37 copies ... I'd say it was up to
the programmer to keep them straightened out properly.
> The reason the term 'indeterminate' is used in this context is that
> the standard makes any use of an 'indeterminate' value (other than
> with an lvalue type other than unsigned char) undefined behavior.
While in a practical sense we all know what it means (or we should,
if we're going to make a living at this stuff), in another sense it
is somewhat ambiguous. After a call to free(), the value of "ptr"
is indeterminate. Does that mean that there is now a random bit
pattern stored in "ptr", or does it mean that we cannot under any
circumstances 'view' the bit pattern stored in "ptr"?
Of course, in the 'real world', it means neither. It simply means
that we gave that memory back to the system and any access to it
leads to undefined behavior.
> Consider a platform like today's common desktop, with memory
> management hardware. Freeing a pointer might cause the block of
> virtual memory that mapped to it to be removed from the program's
> address space. Attempting to dereference the pointer, or even compare
> it with NULL, could trigger an exception when it is loaded into an
> addressing register. That's a pretty good example of undefined
Does this mean I can't copy out the bit pattern and view it?
(say, with a memcpy() into an array of unsigned chars). While
a bit pattern representing a trap may have been copied into "ptr",
I don't think free is _allowed_ to do that.
Here is the question it all boils down to:
Given that the standard specifies the prototype of free() to be
void free(void *ptr)
Is then free() *required* to behave that way? By the definition,
the bit pattern of "ptr" should not change; but is 'compiler magic'
allowed to happen here with a prototype that doesn't explicitly
*show* the value has changed?
Did I ask that clearly, or did I just muddle the waters?
-- Ron Collins Air Defense/RTSC/BCS "I have a plan so cunning, you could put a tail on it and call it a weasel"