effect of free()

Norman Diamond diamond at csl.sony.co.jp
Fri Sep 8 15:42:06 AEST 1989


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.

In article <16022 at vail.ICO.ISC.COM> rcd at ico.ISC.COM (Dick Dunn) writes:

>>Not true.  The "if" only examines the value of the pointer, not what it
>>points to.

In article <248 at seti.inria.fr> jourdan at minos.inria.fr (Martin Jourdan) writes:

>You're wrong, Dick....  Imagine a segmented memory architecture with
>protections, and imagine that the call to "free" above frees the last
>used block in the segment ...
>The morale of the whole story is: DO NOT DO ANYTHING WITH A FREED
>POINTER....

In fact the block cannot be freed by "free."  It can be freed by the
next malloc/calloc, and might be freed by the next realloc.  However,
if there are no *alloc calls between the free and the if, it has to
work.

Why?

Well, because a freed pointer is still valid in a call to realloc
(as long as there are no intervening *alloc calls), and the data still
have to be sitting in limbo, not really quite freed yet.  (Much to the
chagrin of efficiency experts everywhere.)

To cover all cases though:  IT IS MADNESS TO DO ANYTHING WITH A FREED
POINTER.

--
-- 
Norman Diamond, Sony Corporation (diamond at ws.sony.junet)
  The above opinions are inherited by your machine's init process (pid 1),
  after being disowned and orphaned.  However, if you see this at Waterloo or
  Anterior, then their administrators must have approved of these opinions.



More information about the Comp.lang.c mailing list