Skip to content

Lesson 3 of 14 · 20m

Strings Are a Convention: The NUL Terminator and Its Traps

C strings are a convention not a type — strncpy silently drops the terminator, strlcpy and snprintf don't, and strlen trusts the attacker.

C has no string type. It has a convention: a char array, terminated by a '\0' byte, passed around as char * with no length attached. Every catastrophic string bug in C — every unbounded strcpy, every strlen that walks off the end of a packet — comes from forgetting that the NUL is the only boundary marker there is, and nothing enforces it.

The wrong mental model is that strncpy is "the safe strcpy." It isn't, and it was never designed for that job. strncpy was built for fixed-width fields — think the 100-byte name field of a tar header — and it has two traps nobody reads in the man page until the postmortem: if src is shorter than n it zero-pads the rest of the buffer (a quadratic-writes performance bug when people "fix" it with strncpy(buf, src, sizeof buf) in a loop), and if src is n bytes or longer it copies exactly n bytes and writes no terminator. The buffer is now a valid, unterminated byte array that printf/strlen/strcmp will walk straight past.

char name[16];
strncpy(name, user, sizeof name);   /* user is 20 chars: no NUL anywhere */
puts(name);                          /* reads past name into whatever's next */

The three idioms that actually terminate:

snprintf(buf, sizeof buf, "%s", src);   /* always NUL-terminates; returns the
                                           length it *would* have written —
                                           n >= sizeof buf means truncated */
strlcpy(buf, src, sizeof buf);          /* BSD semantics: always terminates,
                                           returns strlen(src); in glibc 2.38+ */
memcpy(buf, src, n);                    /* only after an explicit length check */

snprintf's return value is the detail juniors miss: it's the number of bytes that would have been written excluding the NUL, so int n = snprintf(...); if (n < 0 || (size_t)n >= sizeof buf) is the complete truncation test. strlcpy finally landed in glibc 2.38 (August 2023) after thirty years of BSD-only availability — the industry converged on "always terminate, return source length" as the correct contract, which tells you which one to prefer where it exists.

The quieter bugs live around the terminator:

  • Unbounded strlen/scanf("%s")/gets. strlen on attacker bytes with no NUL is an over-read; scanf("%s", buf) is gets in a trench coat — use %63s with the explicit width, or read with fgets. gets was deleted from the standard in C11 for exactly this reason.
  • The off-by-one NUL. for (i = 0; i <= sizeof buf; i++) writes the terminator one byte past the array — a single NUL byte into whatever follows it, small enough that stack canaries and ASan sometimes miss it, big enough that it's been exploitable.
  • sizeof on the wrong object. sizeof buf is the capacity only in the function that declared the array; everywhere else it's sizeof(char *) — the decay rule from the previous lesson with a fresh victim.
  • strcat/strncat chains. strncat counts room for the copied bytes, not the buffer size — the bound you pass is sizeof dst - strlen(dst) - 1, and getting it wrong is its own bug class. If you find yourself doing that arithmetic, use snprintf at an offset instead.

Try this

Write strncpy(name, src, sizeof name) with src one byte longer than name, then puts(name). Build with gcc -fsanitize=address and watch ASan report a stack-buffer-overflow on the read — not the write — in strlen. The write was "safe"; the missing NUL turned the next read into the bug. Now swap in strlcpy or snprintf and rerun clean.

Field notes

  • snprintf(dst, n, fmt, ...) where fmt is user data is the format-string bug in disguise — the format string must be a literal. The next module covers what %n does to you.
  • strlen returning size_t means strlen(a) - strlen(b) can wrap to a giant unsigned value. It's never what you meant.
  • On a glibc older than 2.38 without strlcpy, snprintf is the portable answer; its cost is formatting machinery you don't need for a plain copy, which is the only real argument memcpy + explicit check wins.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.