The free() thing

Gary M. Samuelson garys at bunker.UUCP
Sat Sep 16 07:10:56 AEST 1989


In article <1989Sep14.022055.5961 at twwells.com> bill at twwells.com (T. William Wells) writes:
>I posted a note on using a pointer after it was freed that seems to
>have become lost. The point is that *any* dpANS compliant compiler,
>on any system, may generate invalid code if you use a pointer after
>it is freed. Here is how:
>
>Free() is defined in the dpANS library. That being the case, the
>compiler is free to assume that the pointer's value is not being used
>legitimately after the call. It knows that the object to which the
>pointer pointed no longer exists, so there is no valid use of the
>pointer's value.

I disagree.  For purposes of debugging, I have written my own
functions to call malloc() and free().  Mymalloc() calls malloc()
and records the pointer returned.  Myfree() checks to make sure that
(1). the pointer I want to free() was one originally obtained by
mymalloc(), and (2) that it has not already been released by myfree().
I claim that this is a valid use for a pointer which no longer points
to anything.

>During code generation, it could mark the location the pointer is
>stored in as dead right after the pointer's value is made available
>for the free call, since it knows that there can be no legitimate
>reason to access the value of the pointer.

No compiler has any business changing the value of a variable
I have declared, except when I have written code to do so.
But even so, suppose there was another copy of that same pointer
in another variable?  How will the compiler know about that one?

>So if you want to write portable programs, you had better assume that
>a freed pointer has no value that you should look at. Because it may
>have no determinate value.

Notice to compiler vendors:
No compiler I want to buy or use is going to exhibit this behavior.
If I want to examine a pointer, I better be able to.

As someone else has said, some day there will be two kinds of C
compiler: standard-conforming, and useful.

Gary Samuelson



More information about the Comp.lang.c mailing list