pointers-memory · intermediate · ~8 min
Quantify the leak rather than just detecting it.
Count how many allocations are still live at the end of an operation trace — that is, how many were leaked.
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.
ops — a NUL-terminated string of 'a' and 'f' characters (may be empty).
Returns the count of allocations never freed (the live depth at the end, never negative).
leak_count("aaf") -> 1
leak_count("af") -> 0
leak_count("aaa") -> 3
leak_count("ff") -> 0 (frees with nothing live are ignored)
Drill: practice one contract before combining it with other skills.
ops — a NUL-terminated string of 'a' and 'f' characters (may be empty).
Returns the count of allocations never freed (the live depth at the end, never negative).
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.
int leak_count(const char *ops) {
/* TODO */
return 0;
}
Letting the count become negative or returning only whether a leak exists.
Empty trace; ignored free at zero; several outstanding allocations; ignored non-operation characters.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.