Free is a function included in the C standard library to deallocate memory on the heap in C and C++.

It is used as follows:

void free(void *ptr);

This will deallocate memory in that space using the pointer that was returned by a malloc call. If ptr is null, the function does nothing.

If that pointer is not a pointer used by malloc earlier or that space has already been freed, it results in UB.

Once freed, this space can once again be used by other [Malloc|malloc] calls.

Pitfalls

  • Free does not change what the pointer returned by malloc is pointing to!
  • Free does not change any other pointers pointing to that memory either!
  • Free does not change or erase the data in freed memory!

Memory Issues

Plenty of memory issues arise from the incorrect use of free().

Some examples include:

Use after Free

Referencing or using a variable after it has been freed. This is considered undefined behavior. The most common cause of this type of error are dangling pointers caused by either allocating a pointer to a variable on the stack, or misuse of third party librairies.

Double Free

Calling free() on the same pointer twice without reallocating to it in between. This can cause really nasty bugs, like corruption of the heap. If the area in memory that that pointer is pointing to gets allocated to some memory by another pointer in the meantime, this also means that when you call free() for the second time, it would be considered “free” by one part of your program, even though there may still be a pointer pointing to that area in memory somewhere else in your program.