Pointers & Memory · intermediate · ~8 min
Follow ownership across branches and distinguish a counter model from actual leak detection.
A leak occurs when allocated storage is no longer reachable for its intended cleanup. A simple allocation/free trace helps you practice accounting, but matching counts alone cannot establish that a real program freed the right objects.
Draw one ownership obligation for each successful allocation. Follow success and error returns: every path must either release that ownership or transfer it to someone responsible for cleanup.
A trace using a for allocation and f for free is a simplified counter exercise. Real programs need object identities: freeing one object twice while forgetting another can produce balanced counts and still be wrong.
Use a memory checker when available and inspect ownership paths as well. Passing a few inputs is not proof that every error path releases its resources.
A leak occurs when allocated storage is no longer reachable for its intended cleanup. A simple allocation/free trace helps you practice accounting, but matching counts alone cannot establish that a real program freed the right objects.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof *p);
if (p == NULL) return 1;
*p = 5;
int result = *p;
free(p);
printf("%d\n", result);
return 0;
}
Expected output on a successful allocation, where applicable:
5
Only a successful allocation creates a cleanup obligation. The successful path consumes that obligation before returning; the failure path owns no allocation.
Account for each successful allocation on every path. Trace counters are teaching models; real leak analysis tracks particular allocations and their owners.