effect of free()

Steve Summit scs at hstbme.mit.edu
Sat Sep 9 17:13:53 AEST 1989


In articles too numerous to mention, hordes of people get badly
upset at the prospect that

	p = malloc(size);
	free(p);
	if(p == NULL)
		...

might cause ugly, undefined behavior such as traps or exceptions.

Look, folks, there are only two valid ways of obtaining valid
pointers in C:

	1. take the address of an object
	2. use malloc()

(well, you can also perform valid arithmetic on already-valid
pointers).  But the line

	if(ptr == NULL)

would not "blow up" for just any values of ptr; it could only
blow up for invalid values of ptr.  The only way for a
previously-valid pointer to become invalid is to pass it to free.
(Objects don't move around; pointers to objects stay valid.)
Having passed a pointer to free, there's no reason to be doing
anything more with it (comparing it to NULL, or anything else).

In article <2059 at munnari.oz.au> ok at cs.mu.oz.au (Richard O'Keefe) writes:
>    are there code sequences which
>	(b) can NOT handle ptr1==ptr2 where one of them used to be a valid
>	    address but isn't just at the moment

Would it bother you if there were?  When would such a situation
realistically come up?  It's not every pointer operation in a
program that becomes suspect under this stricter interpretation;
it's only any (meaningless) operations on pointers after calling
free().  You shouldn't be doing anything with a freed pointer,
other than perhaps setting it to NULL to remind yourself that
you've freed it.

You can, of course, also get an invalid pointer by using an
uninitialized automatic pointer variable, or by doing invalid
pointer arithmetic, but I hope nobody wants those cases to
"work."  (As has been suggested, having the hardware trap such
invalid uses would aid development of correct software.)

I'd say that, if you were using this hypothetical machine that
invalidated pointers upon free and that could later trap
operations (not necessarily dereferencing) on the now-invalid
pointer, you would never notice it (unless your code was already
badly broken.)  I doubt you'd be tempted to boycott the authors
of such compilers or the vendors of such machines (unless there
were mere inefficiencies introduced by, say, allowing comparisons
against NULL pointers while disallowing comparisons against
completely invalid pointers, but that's another story).

Richard mentioned garbage collection; that's a good example of a
situation in which an (avowedly nonportable) program can make
good use of undefined pointer comparisons.  However, even if you
thought your garbage collector was "semi portable," it certainly
wouldn't have worked, without modification, on the sorts of
segmented architectures that are likely to disallow invalid
pointer operations.

                                                Steve Summit



More information about the Comp.lang.c mailing list