Challenge 3: strncpy's Gotcha, and What a Caller Must Do About It — Possible Solution ==================================================================== Per the chapter, strncpy(dest, src, n) copies at most n characters from src into dest. The specific gotcha: if src's actual length is GREATER THAN OR EQUAL TO n, strncpy copies exactly n bytes and stops there -- it does NOT reserve one of those n bytes for a null terminator, and it does not add one after the fact. The result is that dest, in this specific case, may not be a valid, properly-terminated C string at all -- any later function that reads dest expecting a '\0' somewhere (strlen, printf's %s, strcmp, etc.) has no defined stopping point and will keep reading past the end of the intended data, producing the exact buffer-overread class of bug strncpy was meant to prevent in the first place, just from the other end. (Note: if src's length is LESS than n, strncpy behaves safely and does null-terminate, additionally zero-padding the rest of the buffer -- the gotcha only applies to the equal-or-longer case.) What a caller must do afterward to guarantee proper termination: explicitly set the last byte of the destination buffer to '\0' after calling strncpy, regardless of what strncpy itself did -- e.g. char buf[5]; strncpy(buf, some_long_string, 5); buf[4] = '\0'; // forces termination, unconditionally This manually guarantees a null terminator exists within the buffer's own bounds, regardless of whether strncpy happened to leave room for one on its own. WHY THIS WORKS AS AN ANSWER ------------------------------ This states the precise boundary condition that triggers the gotcha (source length >= n, not just "sometimes"), explains the downstream consequence (functions reading past the buffer looking for a '\0' that isn't there), and gives the concrete, standard fix (an explicit manual null-termination step after the call) rather than a vague "be careful" answer.