cybersecurity · beginner · ~15 min

Safe append position

Check capacity before appending.

Challenge

Decide where to append into a buffer only if the result still leaves room for the NUL terminator.

Task

Implement int append_pos(int curlen, int addlen, int cap) that returns the offset to append at, or -1 if it would not fit.

Input

  • curlen: current string length in the buffer.
  • addlen: number of bytes you want to append.
  • cap: total buffer capacity.

Output

Returns int: curlen (the append offset) if curlen + addlen < cap (leaving one byte for the NUL), else -1.

Example

append_pos(3, 4, 16)     ->   3
append_pos(14, 4, 16)    ->   -1   (no room)
append_pos(11, 4, 16)    ->   11   (11+4=15 < 16)

Edge cases

  • The check is strict (< cap) so a byte is always reserved for the terminator.

Input format

Three ints: curlen, addlen, and cap.

Output format

An int: curlen if curlen+addlen < cap, else -1.

Constraints

Reserve one byte for the NUL (strict < cap).

Starter code

int append_pos(int curlen, int addlen, int cap) {
    /* TODO */
    return -1;
}

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