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

