cybersecurity · intermediate · ~15 min
Guarantee a buffer is a valid C string.
Guarantee a raw byte buffer is a valid C string before any str* function runs off its end.
Implement int ensure_terminated(char *buf, int n) that checks the first n bytes of buf and ensures it is NUL-terminated.
buf: a buffer of n bytes that may or may not already contain a NUL.n: the buffer size.n bytes, leave buf unchanged and return 1.buf[n-1] = '\0' and return 0.{'h','i',0,'x','y'} (n=5) -> 1 (already terminated)
{'a','b','c'} (n=3) -> 0 (forces buf[2]='\0')
[0, n) is considered safe (return 1).A char buffer buf and its size n.
An int: 1 if already NUL-terminated, else 0 (after forcing buf[n-1]='\0').
A NUL anywhere in the first n bytes counts as terminated.
int ensure_terminated(char *buf, int n) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.