cybersecurity · beginner · ~15 min
Check capacity before appending.
Decide where to append into a buffer only if the result still leaves room for the NUL terminator.
Implement int append_pos(int curlen, int addlen, int cap) that returns the offset to append at, or -1 if it would not fit.
curlen: current string length in the buffer.addlen: number of bytes you want to append.cap: total buffer capacity.Returns int: curlen (the append offset) if curlen + addlen < cap (leaving one byte for the NUL), else -1.
append_pos(3, 4, 16) -> 3
append_pos(14, 4, 16) -> -1 (no room)
append_pos(11, 4, 16) -> 11 (11+4=15 < 16)
< cap) so a byte is always reserved for the terminator.Three ints: curlen, addlen, and cap.
An int: curlen if curlen+addlen < cap, else -1.
Reserve one byte for the NUL (strict < cap).
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.