pointers-memory · intermediate · ~15 min

Detect a use-after-free

Recognise the use-after-free pattern as a state condition.

Challenge

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).

Task

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.

Input

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

Output

Returns 1 if a use-after-free occurs, otherwise 0.

Example

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

Edge cases

  • A 'u' after re-allocation is fine (the resource is live again).
  • Empty string: 0.

Input format

ops — a string of 'a', 'f', 'u' chars (may be empty).

Output format

1 if any use happens while freed, else 0.

Constraints

A use after re-allocation is not a UAF.

Starter code

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.