cybersecurity · intermediate · ~15 min

Bounds-safe byte read for a fuzzer

Defend every access against the fuzzer's arbitrary size.

Challenge

A fuzz target receives arbitrary data/size, so every byte access must be bounds-checked or the fuzzer finds the overflow.

Task

Implement int safe_byte(const unsigned char *data, int size, int idx) that returns data[idx] if the index is in range, else -1.

Input

  • data, size: the fuzzer-supplied buffer and its length (the grader passes fixed values).
  • idx: the index to read.

Output

Returns int: the byte value data[idx] if 0 <= idx < size, else -1.

Example

data {10,20,30}, size 3
safe_byte(data, 3, 1)   ->   20
safe_byte(data, 3, 3)   ->   -1   (out of range)
safe_byte(data, 0, 0)   ->   -1   (empty buffer)

Edge cases

  • A negative index or idx >= size returns -1.
  • An empty buffer (size == 0) always returns -1.

Rules

  • Check 0 <= idx < size before indexing.

Input format

A byte buffer data with length size, and an index idx.

Output format

An int: the byte at idx if in range, else -1.

Constraints

Return -1 unless 0 <= idx < size.

Starter code

int safe_byte(const unsigned char *data, int size, int idx) {
    /* TODO */
    return -1;
}

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