effect of free()

Dick Dunn rcd at ico.ISC.COM
Fri Aug 18 08:57:27 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.

Not true.  The "if" only examines the value of the pointer, not what it
points to.  free(ptr) does not modify ptr; it can't.  Assuming the malloc
succeeded (and assuming an appropriate in-scope declaration of malloc, if
you want to be fussy), the code as written will work, and the body of the
"if" will not be executed, since ptr will be non-null from the malloc.

The trouble will only begin when you try to look at *ptr.

shut up,
inews!
I
know
what
I'm
doing.
-- 
Dick Dunn     rcd at ico.isc.com    uucp: {ncar,nbires}!ico!rcd     (303)449-2870
   ...Are you making this up as you go along?



More information about the Comp.lang.c mailing list