pointers-memory · intermediate · ~15 min

Validate a resource lifecycle

Encode all the memory-safety rules as a small state machine.

Challenge

Validate that a resource's lifecycle is well-formed: you may only use or free something that is currently allocated, you may not double-free, and you may not allocate over a resource that is already live.

Task

Implement int valid_lifecycle(const char *ops) over a trace using 'a' (allocate), 'f' (free), 'u' (use). Return 1 if every operation respects its precondition, else 0. No main — the grader calls it.

Rules for each operation

  • 'a' is valid only when the resource is not currently allocated-and-live (after a free, re-allocation is allowed).
  • 'f' is valid only when the resource is currently live (no free-before-alloc, no double-free).
  • 'u' is valid only when the resource is currently live (no use-before-alloc, no use-after-free).

Input

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

Output

Returns 1 if the whole sequence is valid, else 0.

Example

valid_lifecycle("auf")    ->   1
valid_lifecycle("afaf")   ->   1   (allocate again after freeing)
valid_lifecycle("ufa")    ->   0   (use before allocate)
valid_lifecycle("aff")    ->   0   (double free)
valid_lifecycle("afu")    ->   0   (use after free)

Edge cases

  • Empty string: valid (returns 1).

Input format

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

Output format

1 if every operation respects its precondition, else 0.

Constraints

No use/free before alloc; no double-free; no use-after-free; re-alloc after free is allowed.

Starter code

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

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