free (NULL);

D. Richard Hipp drh at romeo.cs.duke.edu
Tue May 8 23:14:55 AEST 1990


In article <1194 at wet.UUCP> noah at 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()".



More information about the Comp.lang.c mailing list