effect of free()

Karl Heuer karl at haddock.ima.isc.com
Sat Aug 19 04:06:43 AEST 1989


In article <568 at augean.OZ> Ian Dall writes:
>In article <1989Aug17.005548.745 at twwells.com> bill at twwells.com (T. William Wells) writes:
>>	free(ptr);
>>	if (ptr == 0) ...
>>The if might cause a trap when the value of ptr is accessed.

>Well you should strictly do something like
>      if (ptr == (char *) 0) ...

Only for style; the cast doesn't change the semantics.

>If that causes a trap your compiler and/or operating system is
>definitely broken.  Ptr is just a local variable ...

The issue is not whether the value of ptr has changed.  Some architectures
distinguish between arithmetic registers and address registers, and refuse to
allow arbitrary garbage to be loaded into an address register.  If free()
actually releases the segment to the operating system (I don't know of any
implementations that do, but the possibility is there), then the value of ptr,
although unchanged, could now be unloadable.  In other words, not only *ptr
but also ptr itself are unusable.

>The compiler doesn't know what malloc and free do. For all the
>compiler knows malloc and free could be functions you wrote with
>completely different semantics.

That's implementation-dependent.  For all you know, malloc() and free() are
builtins on my compiler.

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list