0

Ì used to make sure a pointer was not null before freeing it, so I would normally destroy dynamically created structs like this:

Node *destroy_node(Node *node) {
    if (node) {
        free(node);
    }
    return NULL;
}

But CERT MEM34 suggests that since free() accepts null pointers, I could as well write

Node *destroy_node(Node *node) {
    free(node);
    return NULL;
}

Is that correct?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
AdHominem
  • 1,204
  • 3
  • 13
  • 32

2 Answers2

1

Yes, passing NULL (a null-pointer constant) to free() is perfectly valid.

Quoting C11, chapter §7.22.3.3, (emphasis mine)

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. [...]

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Yes, passing NULL to free is a no-op.

Excerpt from n1570 (C11 final draft):

7.22.3.3 The free function Synopsis
1 #include void free(void *ptr);
Description
2 The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
Returns
3 The free function returns no value.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118