cybersecurity · intermediate · ~15 min

Ensure NUL termination

Guarantee a buffer is a valid C string.

Challenge

A buffer of n bytes may hold non-terminated data. Implement int ensure_terminated(char *buf, int n) returning 1 if it already contains a NUL in the first n bytes (safe), otherwise force buf[n-1] = '\0' and return 0.

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.