pointers-memory · intermediate · ~15 min

Are allocations balanced?

Model alloc/free balance — the essence of leak-freedom.

Challenge

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.

Task

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.

Input

ops — a NUL-terminated string of 'a' and 'f' characters (may be empty).

Output

Returns 1 if the running depth never goes below 0 and ends at exactly 0; otherwise 0.

Example

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

Edge cases

  • Empty string: balanced (returns 1).
  • Depth goes negative at any point: returns 0.
  • Depth positive at the end (a leak): returns 0.

Input format

ops — a string of 'a' (alloc) and 'f' (free) chars (may be empty).

Output format

1 if balanced (depth never negative, ends at 0), else 0.

Starter code

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.