effect of free()

Tom Karzes karzes at mfci.UUCP
Fri Sep 8 04:21:23 AEST 1989


In article <248 at seti.inria.fr> jourdan at minos.inria.fr (Martin Jourdan) writes:
}>> 	char    *ptr;
}>> 
}>> 	ptr = malloc(1);
}>> 	...
}>> 	free(ptr);
}>> 	...
}>> 	if (ptr == 0) ...
}>> 
}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.

Nonsense.  There are no indirect or indexed references in the code above,
hence no opportunities for invalid address traps.  Period.  It might be
invalid to attempt to dereference ptr, e.g., "if (*ptr == 0) ...", but
no such attempt has been made in the code.  If malloc returns 0x1000,
then ptr contains 0x1000 and 0x1000 is a valid address.  After the
call to free, 0x1000 may no longer be a valid address, so *ptr may
cause an invalid address trap.  But ptr itself still contains 0x1000,
and may be accessed regardless of whether or not 0x1000 is mapped,
so long as 0x1000 is not dereferenced.

}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.

Sorry, but NULL is no more valid than the pointer returned by malloc.
You are not allowed to dereference NULL (many machines do allow it,
and return 0, but this merely fixes broken programs which do not
proprtly guard against NULL pointers).  The one thing you can count
on is that NULL will compare unequal to any valid address, whereas
your moldy old pointer may match some newly allocated address.  But
neither may be dereferenced.



More information about the Comp.lang.c mailing list