Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!mcsun!ukc!edcastle!aiai!richard From: richard@aiai.ed.ac.uk (Richard Tobin) Newsgroups: comp.lang.c Subject: Re: free (NULL) Message-ID: <2574@skye.ed.ac.uk> Date: 25 May 90 18:01:55 GMT References: <1771@mindlink.UUCP> <36491@think.Think.COM> <1718@necisa.ho.necisa.oz> <2507@skye.ed.ac.uk> <1724@necisa.ho.necisa.oz> Reply-To: richard@aiai.UUCP (Richard Tobin) Organization: AIAI, University of Edinburgh, Scotland Lines: 36 In article <1724@necisa.ho.necisa.oz> boyd@necisa.ho.necisa.oz (Boyd Roberts) writes: >>There are plenty of cases where a careful programmer >>might do "if(p) free(p)" with complete clarity and correctness. >I hope this `careful programmer' never uses malloc(). Er, I hope they do. Otherwise they're making a mistake in using free(). >If you allocate >something, there comes a time when it should be free'd. Not because >it `might' be a good idea, but because it is correct to do so. *Sigh* Yes, *if* you allocate something, you probably want to free it later. But what if you *didn't* allocate it? Then you *don't* want to free it. It's completely reasonable, for example, to have a structure with fields that might either be filled in (with a string containing a name, perhaps) or be null (because the name isn't known, perhaps). In such a case, when you free the structure, "if(s->name) free(s->name)" is exactly what you need to do. >free(NULL) has simplicity at the cost of clarity, correctness and portability. >Successfully using an error return value is not a programming pearl. If the NULL you pass to free was handed to you by malloc() than you should almost certainly have already checked for it. Even in this case, it may simplify your error cleanup code if you just call free() anyway. But this wasn't one of the situations I had in mind. -- Richard -- Richard Tobin, JANET: R.Tobin@uk.ac.ed AI Applications Institute, ARPA: R.Tobin%uk.ac.ed@nsfnet-relay.ac.uk Edinburgh University. UUCP: ...!ukc!ed.ac.uk!R.Tobin