pointers-memory · intermediate · ~8 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
Drill: practice one contract before combining it with other skills.
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.
ops is a non-NULL terminated trace. Count a as allocation and f as free; other characters are ignored. Running count must fit int. This counter model does not track object identity or execute allocations.
int balanced_allocs(const char *ops) {
/* TODO */
return 0;
}
Checking only final counts and accepting a free before its allocation.
Empty trace is balanced; reject any negative prefix even if final count is zero; reject a positive final count.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.