pointers-memory · intermediate · ~8 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).Drill: practice one contract before combining it with other skills.
ops — a NUL-terminated string of 'a', 'f', 'u' characters (may be empty).
Returns 1 if a use-after-free occurs, otherwise 0.
ops is non-NULL and terminated. Initially the freed flag is clear; a clears it, f sets it, u while set reports a use-after-free. Other characters are ignored. This is a simplified flag model, not full lifecycle validation.
int has_use_after_free(const char *ops) {
/* TODO */
return 0;
}
Treating every use as invalid or forgetting to clear the flag on a.
Empty trace; use before any free is not flagged by this limited model; reallocation clears the flag; a later freed-state use is flagged.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.