pointers-memory · intermediate · ~15 min
Recognise the use-after-free pattern as a state condition.
Detect a use-after-free in an operation trace: a "use" that happens while the resource is in the freed state (and hasn't been re-allocated since).
Implement int has_use_after_free(const char *ops) over a trace where 'a' allocates, 'f' frees, and 'u' uses a single resource. Return 1 if any 'u' occurs while the resource is freed, else 0. No main — the grader calls it.
ops — a NUL-terminated string of 'a', 'f', 'u' characters (may be empty).
Returns 1 if a use-after-free occurs, otherwise 0.
has_use_after_free("afu") -> 1 (use while freed)
has_use_after_free("auf") -> 0 (use before free)
has_use_after_free("afau") -> 0 (re-allocated before the use)
has_use_after_free("au") -> 0
'u' after re-allocation is fine (the resource is live again).ops — a string of 'a', 'f', 'u' chars (may be empty).
1 if any use happens while freed, else 0.
A use after re-allocation is not a UAF.
int has_use_after_free(const char *ops) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.