validity of free() on later pointer operations

Edward Birch edward at runxtsa.runx.oz.au
Wed Jul 11 13:07:54 AEST 1990


>	In article <1990Jul3.185032.8434 at indetech.com>
>				schmidt at indetech.UUCP (Doug Schmidt) writes:
>	>	char *s = malloc (n);
>	>	/* ... */
>	>	free (s);
>	>	s = 0; /* Is this assignment always legal? */
>	>

I quote the manual here:
	The argument to "free" is a pointer to a block previosly allocated
	by "malloc"; after "free" is performed this space is made available
	for further allocation, but its contents are left undisturbed.

The above manual entry implies that the following is correct although
*strongly* unadvisible.

	char	* ptr = malloc(5); /* assume malloc doesn't fail */

	/* .... */
	ptr[0] = 10;
	free(ptr);
	printf("It's ok to access data after a call to free %d\n", ptr[0]);
	
While the above may be ok for a programmer who really think's he/she knows
what they are doing. I strongly suspect that it will cause problems when
porting to other operating systems or when being maintained by other
programmers.

An assignment of "ptr = 0;" in the above example after the "free(ptr);"
will stop accesses of the pointer from that point on by causing a core
dump (on unix) you won't be nearly so lucky on ms-dos or like systems.

This will aid testing & debugging of the program. 

In conclusion the assignment of "s = 0;" is always valid.

Edward Birch

UUCP:   seismo!munnari!runx.oz!edward   ACSnet:  edward at runx.oz
ARPA:   edward%runx.oz at seismo.css.gov   CSNET:   edward at runx.oz



More information about the Comp.lang.c mailing list