cybersecurity · intermediate · ~15 min

Ensure NUL termination

Guarantee a buffer is a valid C string.

Challenge

Guarantee a raw byte buffer is a valid C string before any str* function runs off its end.

Task

Implement int ensure_terminated(char *buf, int n) that checks the first n bytes of buf and ensures it is NUL-terminated.

Input

  • buf: a buffer of n bytes that may or may not already contain a NUL.
  • n: the buffer size.

Output

  • If a NUL already exists within the first n bytes, leave buf unchanged and return 1.
  • Otherwise force buf[n-1] = '\0' and return 0.

Example

{'h','i',0,'x','y'} (n=5)   ->   1   (already terminated)
{'a','b','c'} (n=3)         ->   0   (forces buf[2]='\0')

Edge cases

  • A buffer that already has a NUL anywhere in [0, n) is considered safe (return 1).

Input format

A char buffer buf and its size n.

Output format

An int: 1 if already NUL-terminated, else 0 (after forcing buf[n-1]='\0').

Constraints

A NUL anywhere in the first n bytes counts as terminated.

Starter code

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.