cybersecurity · intermediate · ~15 min
Validate an offset+length against a buffer, overflow-aware.
Validate an offset-plus-length against a buffer before slicing — the check length-prefixed parsers skip at their peril.
Implement int range_ok(int start, int len, int total) that returns 1 if reading len bytes starting at offset start stays within a total-byte buffer, else 0.
start: the starting offset.len: the number of bytes to read.total: the total buffer size.Returns int: 1 if start >= 0, len >= 0, and start + len <= total; else 0.
range_ok(2, 3, 10) -> 1
range_ok(7, 3, 10) -> 1 (ends exactly at total)
range_ok(8, 3, 10) -> 0 (runs past the end)
range_ok(-1, 3, 10) -> 0
total is valid.start or len is invalid.Three ints: start, len, and total.
An int: 1 if start>=0 && len>=0 && start+len<=total, else 0.
A range ending exactly at total is valid.
int range_ok(int start, int len, int total) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.