pointers-memory · intermediate · ~15 min
Model alloc/free balance — the essence of leak-freedom.
Decide whether a sequence of allocate/free operations is perfectly balanced — every allocation eventually freed, and never a free with nothing live. This models leak-freedom as a depth counter that must never go negative and must end at zero.
Implement int balanced_allocs(const char *ops) over a trace string where 'a' means allocate and 'f' means free. Return 1 if the trace is balanced, else 0. No main — the grader calls it.
ops — a NUL-terminated string of 'a' and 'f' characters (may be empty).
Returns 1 if the running depth never goes below 0 and ends at exactly 0; otherwise 0.
balanced_allocs("af") -> 1
balanced_allocs("aaff") -> 1
balanced_allocs("aff") -> 0 (extra free / underflow)
balanced_allocs("fa") -> 0 (free before any alloc)
balanced_allocs("") -> 1
ops — a string of 'a' (alloc) and 'f' (free) chars (may be empty).
1 if balanced (depth never negative, ends at 0), else 0.
int balanced_allocs(const char *ops) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.