Path: utzoo!attcan!uunet!munnari.oz.au!metro!ipso!runxtsa!edward From: edward@runxtsa.runx.oz.au (Edward Birch) Newsgroups: comp.lang.c Subject: Re: validity of free() on later pointer operations Summary: Unfortunately pointers are valid after "free" Message-ID: <1956@runxtsa.runx.oz.au> Date: 11 Jul 90 03:07:54 GMT References: <1990Jul3.185032.8434@indetech.com> <1990Jul03.233255.2616@virtech.uucp> Organization: RUNX Unix Timeshare. Sydney, Australia. Lines: 40 > In article <1990Jul3.185032.8434@indetech.com> > schmidt@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@runx.oz ARPA: edward%runx.oz@seismo.css.gov CSNET: edward@runx.oz