Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!cs.utexas.edu!sdd.hp.com!uakari.primate.wisc.edu!xanth!mcnc!duke!romeo!drh From: drh@romeo.cs.duke.edu (D. Richard Hipp) Newsgroups: comp.lang.c Subject: Re: free (NULL); Keywords: free Message-ID: <19461@duke.cs.duke.edu> Date: 8 May 90 13:14:55 GMT References: <1194@wet.UUCP> Sender: news@duke.cs.duke.edu Reply-To: drh@cs.duke.edu Organization: Duke University CS Dept.; Durham, NC Lines: 39 In article <1194@wet.UUCP> noah@wet.UUCP (Noah Spurrier) writes: > >Is there anything wrong with freeing a NULL? pointer? > >char *squirl() >{ > static char *test = NULL; > free (test); > test = (char *) malloc (100); > return (test); >} > >This function is run many times so iI do not want to protect it with an if >because the if would only be useful for the first time it is run, after that >it just eats up run time. 1. Different implementation do different things with NULL pointers passed to free(). I find it best to assume that it is illegal to not give a null pointer to free(). 2. The amount of time used by an "if" statement to protect the free(), is insignificant compared to the amount of time used by free() itself, and is REALLY insignificant compared to the amount of time used by malloc(). Use an "if". 3. If you are always freeing and mallocing a chunk of memory the same size, then why not just allocate a static array and not mess with free() and malloc() at all. Such will accomplish exactly the same thing as free() followed by malloc(), but with considerably fewer machine cycles. Example: char *squirl() { static char test[100]; return test; } 4. If you are doing something more complex than your example shows, consider using "realloc()".