free(3)

C library function

Returns a block from malloc, calloc or realloc to the heap. free(NULL) is safe; freeing twice, or a pointer that was never allocated, is undefined behavior.

Synopsis
#include <stdlib.h>
void free(void *ptr);

Description

free hands a heap block back so that it can be reused. Its argument must be an address returned by malloc(3), calloc(3) or realloc(3), exactly as it was returned. Not a pointer into the middle of the block, not a stack variable, not a string literal.

Only one case is completely safe: free(NULL) does nothing. The standard guarantees it, and it spares you a pile of if (p != NULL) checks before every release. Everything else is yours to watch. Freeing the same block twice, or passing a pointer that did not come from the heap, is undefined behavior. With glibc (a typical Linux system), it shows up as a message such as free(): double free detected in tcache 2 or free(): invalid pointer followed by Aborted; with musl (Alpine, the environment of Grademe exercises), as a plain segmentation fault. Both cases are covered in double free detected.

Return value

None: free returns void. After the call, the pointer you passed no longer refers to anything valid, and reading it or freeing it again is undefined behavior. The useful habit is free(p); p = NULL;, since a later free(NULL) will do nothing.

Example

free.c
#include <stdio.h>#include <stdlib.h>
int main(void){    char *name = NULL;
    free(name);                      /* no effect, and that is guaranteed */    name = malloc(8);    if (name == NULL)        return 1;    free(name);    name = NULL;                     /* no dangling pointer left */    return 0;}

Pitfalls

  • Double free: freeing the same block twice. Set the pointer to NULL after the first call.

  • Freeing a shifted pointer (free(p + 1), or a p you incremented in a loop): keep the original pointer to hand back.

  • free on a stack variable or a string literal: those addresses do not come from the heap.

  • Using the block after free (use after free): the memory gets recycled, and its contents no longer belong to you.

C

free_str_array

Write free_str_array, which frees every string of a NULL-terminated array before the array itself and returns how many strings it freed.

Open the exercise

Now write it yourself.