effect of free()

Ian Dall idall at augean.OZ
Fri Aug 18 17:37:31 AEST 1989


In article <1989Aug17.005548.745 at twwells.com> bill at twwells.com (T. William Wells) writes:
-In article <3777 at buengc.BU.EDU> bph at buengc.bu.edu (Blair P. Houghton) writes:
-: In article <320 at cubmol.BIO.COLUMBIA.EDU> ping at cubmol.UUCP (Shiping Zhang) writes:
-: I guess the word is, once space is freed, don't even try to get data
-: out of it.  It's risky at least, and nonportable without question.
-
-Actually, things are worse than that: once the space is freed, don't
-even *look* at the pointer. 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.

Well you should strictly do something like 

      if (ptr == (char *) 0) ...

If that causes a trap your compiler and/or operating system is
definitely broken. Ptr is just a local variable and you can compare it
with anything of the appropriate type (a pointer to a char). Free does
not (and cannot since C is call by value) alter the quantity in ptr.
Free DOES make *ptr meaningless but not ptr.

The compiler doesn't know what malloc and free do. For all the
compiler knows malloc and free could be functions you wrote with
completely different semantics.

-- 
 Ian Dall           life (n). A sexually transmitted disease which afflicts
                              some people more severely than others.
idall at augean.oz



More information about the Comp.lang.c mailing list