cybersecurity · beginner · ~15 min

Safe write length

Cap a write at the buffer size.

Challenge

Clamp a requested write length down to what the buffer can actually hold — turning a would-be overflow into a safe truncation.

Task

Implement int safe_write_len(int want, int buf_size) that returns how many bytes you can safely write.

Input

  • want: the number of bytes you would like to write.
  • buf_size: capacity of the destination buffer.

Output

Returns int: the smaller of want and buf_size, but never negative (a negative want yields 0).

Example

safe_write_len(20, 16)   ->   16   (capped)
safe_write_len(8, 16)    ->   8
safe_write_len(-1, 16)   ->   0

Edge cases

  • A negative want returns 0.

Input format

Two ints: want and buf_size.

Output format

An int: min(want, buf_size), floored at 0.

Constraints

Never return a negative value.

Starter code

int safe_write_len(int want, int buf_size) {
    /* TODO */
    return 0;
}

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