pointers-memory · intermediate · ~8 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.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

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

Output format

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

Constraints

ops is a non-NULL terminated trace. a increments, f decrements only when positive, and other characters are ignored; count fits int. Return remaining count, not a boolean.

Starter code

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

Common mistakes

Letting the count become negative or returning only whether a leak exists.

Edge cases to handle

Empty trace; ignored free at zero; several outstanding allocations; ignored non-operation characters.

Up next

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