effect of free()

jourdan martin joseph jourdan at seti.inria.fr
Fri Aug 18 21:59:33 AEST 1989


In article <16022 at vail.ICO.ISC.COM> rcd at ico.ISC.COM (Dick Dunn) writes:
>bill at twwells.com (T. William Wells) writes:
>> ...For example, the following code fragment is nonportable:
>> 
>> 	char    *ptr;
>> 
>> 	ptr = malloc(1);
>> 	...
>> 	free(ptr);
>> 	...
>> 	if (ptr == 0) ...
>> 
>> The if might cause a trap when the value of ptr is accessed.
>
>Not true.  The "if" only examines the value of the pointer, not what it
>points to.

You're wrong, Dick.  Someone else already pointed it out, but let me
make it clear again.  Imagine a segmented memory architecture with
protections, and imagine that the call to "free" above frees the last
used block in the segment and that "free" is clever enough to
determine it and decides to release the segment to the OS, thus making
the whole segment invalid (this is perfectly conceivable, and not
forbidden by any ``standard''; actually I'd love to see some
programs/processes decrease their memory size when they no longer use
it).  Then merely loading the value of "ptr" in a register to test it
against 0 will cause a invalid-address trap.

The morale of the whole story is: DO NOT DO ANYTHING WITH A FREED
POINTER.  To make things safer, each time I free a pointer variable,
the next statement is to copy some valid pointer value (usually NULL)
into it.  Of course, that does not solve the aliasing problem which
was the basis of the whole discussion, but that alleviates many
problems.

Martin Jourdan <jourdan at minos.inria.fr>, INRIA, Rocquencourt, France.
My employers have no opinion and they guarantee my freedom of expression.
-- 

Martin Jourdan <jourdan at minos.inria.fr>, INRIA, Rocquencourt, France.
My employers have no opinion and they guarantee my freedom of expression.



More information about the Comp.lang.c mailing list