pointers-memory · intermediate · ~15 min

Count leaked allocations

Quantify the leak rather than just detecting it.

Challenge

Count how many allocations are still live at the end of an operation trace — that is, how many were leaked.

Task

Implement int leak_count(const char *ops) over a trace where 'a' allocates and 'f' frees a live allocation. An 'f' when nothing is live is ignored. Return the number of allocations still outstanding at the end. No main — the grader calls it.

Input

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

Output

Returns the count of allocations never freed (the live depth at the end, never negative).

Example

leak_count("aaf")   ->   1
leak_count("af")    ->   0
leak_count("aaa")   ->   3
leak_count("ff")    ->   0   (frees with nothing live are ignored)

Edge cases

  • Frees with no live allocation are ignored (the count never goes below 0).
  • Empty string: 0.

Input format

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

Output format

The number of allocations still live at the end.

Constraints

A free with nothing live is ignored; the count never goes negative.

Starter code

int leak_count(const char *ops) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.