effect of free()

Jeff Rosenfeld jdr+ at andrew.cmu.edu
Wed Sep 13 07:40:50 AEST 1989


> Excerpts from netnews.comp.lang.c: 18-Aug-89 Re: effect of free()
> jourdan m. joseph at seti.i (1729)

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


I can't believe this went so long without a response. Dick is correct;
@i[you] are mistaken, Jourdan. Keep in mind that pointers are stored in
memory just like any other data types and can be loaded into
general-purpose registers. No architecture of which I am aware does
protection checking when loading data into a general purpose register.
Similarly, the only segemented architecture with which I am familiar
(80*86) does even allow any operations on segment registers save load,
push, and validate (or some such).  In other words, there is no fear of
protection violation (even with a segemented architecture) until you
attempt to dereference a pointer. The key is that with segments,
dereferencing begins by loading a segement register. Get it?

BTW, the "non-portable" code given is unlikely to work in any event
because if the malloc() call fails then you're calling free(NULL) which
is very likely to cause a seg fault in any protected environment.

			- Jeff.



More information about the Comp.lang.c mailing list