cybersecurity · intermediate · ~15 min

Is a sub-range valid?

Validate an offset+length against a buffer, overflow-aware.

Challenge

Validate an offset-plus-length against a buffer before slicing — the check length-prefixed parsers skip at their peril.

Task

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.

Input

  • start: the starting offset.
  • len: the number of bytes to read.
  • total: the total buffer size.

Output

Returns int: 1 if start >= 0, len >= 0, and start + len <= total; else 0.

Example

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

Edge cases

  • A range ending exactly at total is valid.
  • Negative start or len is invalid.

Input format

Three ints: start, len, and total.

Output format

An int: 1 if start>=0 && len>=0 && start+len<=total, else 0.

Constraints

A range ending exactly at total is valid.

Starter code

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.