liveBook · Manning

Free

As explained in Modern C, Third Edition

free is a C library function that releases dynamically allocated storage previously obtained from a compatible allocation function.

free releases dynamically allocated storage when the object is no longer needed. Allocation and release form an ownership pair: every successful allocation needs a corresponding free, while every free must receive a pointer returned by a compatible allocation function. section 13.1.2 section 13.1

Release a dynamically allocated array

size_t length = livingPeople(); double* largeVec = malloc(length * sizeof *largeVec); for (size_t i = 0; i < length; ++i) largeVec[i] = 0.0; /* use largeVec */ free(largeVec); The final call releases the storage obtained by malloc. Omitting it leaves a memory leak, which can contribute to resource exhaustion, poor performance, or crashes. section 13.1 section 13.1.2

Apply these validity rules:

  • Pass only a pointer returned by malloc, calloc, aligned_alloc, or realloc, or pass a null pointer. section 13.1.2
  • Do not free an automatic variable, compound literal, pointer into the middle of an allocation, or an object already freed. section 13.1.2
  • Count ownership across function boundaries; the allocation and its release need not occur in the same function. section 13.1.2
  • Treat realloc carefully: when it succeeds on an existing object, it can deallocate the old storage while allocating replacement storage. section 13.1.2

Cleanup must also run on error paths. A function that allocates a buffer and later encounters an I/O error can use a shared cleanup label and goto to ensure free is reached instead of leaking the buffer. section 15.6

#include <stdlib.h>
void* malloc(size_t size);
void free(void* ptr);
void* calloc(size_t nmemb, size_t size);
void* realloc(void* ptr, size_t size);
void* aligned_alloc(size_t alignment, size_t size);

Browse the standard-library declarations for malloc, free, calloc, realloc, and aligned_alloc. section 13.1

How Modern C, Third Edition covers it

How deep it goes
Defines valid pointer origins, pairing rules, leaks, realloc interactions, and cleanup control flow, but does not descend into allocator internals.
Examples
Uses an allocated double array, a printing buffer, realloc failure, I/O failure, and a shared goto cleanup path.
What it assumes
Assumes pointers, functions, arrays, and basic C allocation, while teaching allocation pairing and cleanup from concrete examples.
What you can do after
Apply ownership accounting and cleanup paths that release allocated storage without leaks or invalid frees.
How it connects
Connects dynamic allocation with malloc, calloc, aligned_alloc, realloc, memory leaks, ownership, and error handling.

Also explained in

Compare how 2 books explain free →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.