0Pricing
C Academy · Lesson

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

  1. Allocating an Array
  2. Growing with realloc
  3. A Reusable Vector Type
  4. Freeing and Avoiding Leaks
← Back to C Academy