cybersecurity · intermediate · ~15 min
Defend every access against the fuzzer's arbitrary size.
A fuzz target receives arbitrary data/size, so every byte access must be bounds-checked or the fuzzer finds the overflow.
Implement int safe_byte(const unsigned char *data, int size, int idx) that returns data[idx] if the index is in range, else -1.
data, size: the fuzzer-supplied buffer and its length (the grader passes fixed values).idx: the index to read.Returns int: the byte value data[idx] if 0 <= idx < size, else -1.
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)
idx >= size returns -1.size == 0) always returns -1.0 <= idx < size before indexing.A byte buffer data with length size, and an index idx.
An int: the byte at idx if in range, else -1.
Return -1 unless 0 <= idx < size.
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.