cybersecurity · beginner · ~15 min
Cap a write at the buffer size.
Clamp a requested write length down to what the buffer can actually hold — turning a would-be overflow into a safe truncation.
Implement int safe_write_len(int want, int buf_size) that returns how many bytes you can safely write.
want: the number of bytes you would like to write.buf_size: capacity of the destination buffer.Returns int: the smaller of want and buf_size, but never negative (a negative want yields 0).
safe_write_len(20, 16) -> 16 (capped)
safe_write_len(8, 16) -> 8
safe_write_len(-1, 16) -> 0
want returns 0.Two ints: want and buf_size.
An int: min(want, buf_size), floored at 0.
Never return a negative value.
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.