ManticMoo.COM -> Jeff's Articles -> Programming Articles -> Calling free() on a NULL pointer

Calling free() on a NULL pointer

by Jeffrey P. Bigham

Sometimes it is convenient to allow a pointer that you call free on to point to a null location (an example is given below). Fortunately, that is perfectly fine to do. free() does absolutely nothing on a NULL pointer. One use of this is to declare a variable that a function might use but only allocate space for it if you need to and just always free the memory at the end. That way you don't have to worry about remembering to free it at a number of locations along the way.

An Example



char *my_string = NULL;

if(some_condition) {
  my_string = malloc(sizeof(char) * STRING_LENGTH);
} else if(another_condition) {
  my_string = malloc(sizeof(char) * STRING_LENGTH2);
}

free(my_string);


This is perfectly fine to do and even if neither condition is met your call to free is valid because free() does nothing on a NULL pointer.

ManticMoo.COM -> Jeff's Articles -> Programming Articles -> Calling free() on a NULL pointer