free – a quick summary

So, let's summarize the key points regarding the usage of the free API:

  • The parameter passed to free(3) must be a value returned by one of the malloc(3) family APIs (malloc(3), calloc, or realloc[array]).
  • free has no return value.
  • Calling free(ptr) does not set ptr to NULL (that would be nice, though).
  • Once freed, do not attempt to use the freed memory.
  • Do not attempt to free the same memory chunk more than once (it's a bug UB).
  • For now, we will assume that freed memory goes back to the system.
  • For Heaven's sake, do not forget to free memory that was dynamically allocated earlier. The forgotten memory is said to have leaked out and that's a really hard bug to catch! Luckily, there are tools that help us catch these ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.