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

Why this matters

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

Input format

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

Output format

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

Constraints

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.

Starter code

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

Common mistakes

Treating every use as invalid or forgetting to clear the flag on a.

Edge cases to handle

Empty trace; use before any free is not flagged by this limited model; reallocation clears the flag; a later freed-state use is flagged.

Up next

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