Freeing and Avoiding Leaks
Clean up correctly.
Every malloc Needs a free
Heap memory stays reserved until you release it with free. If you lose the only pointer to a block without freeing it, that memory is leaked.
Leaks pile up over time and can exhaust memory in long-running programs.
int *a = malloc(100 * sizeof(*a));
/* ... use a ... */
free(a);What free Actually Does
free(p) returns the block to the allocator so it can be reused. It does not change the value of p itself.
After free, p still points at the old address, which is now invalid. Touching it is undefined behavior.
free(p);
/* p is now a dangling pointer */All lessons in this course
- Allocating an Array
- Growing with realloc
- A Reusable Vector Type
- Freeing and Avoiding Leaks