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.strlenon attacker bytes with no NUL is an over-read;scanf("%s", buf)isgetsin a trench coat — use%63swith the explicit width, or read withfgets.getswas 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. sizeofon the wrong object.sizeof bufis the capacity only in the function that declared the array; everywhere else it'ssizeof(char *)— the decay rule from the previous lesson with a fresh victim.strcat/strncatchains.strncatcounts room for the copied bytes, not the buffer size — the bound you pass issizeof dst - strlen(dst) - 1, and getting it wrong is its own bug class. If you find yourself doing that arithmetic, usesnprintfat 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, ...)wherefmtis user data is the format-string bug in disguise — the format string must be a literal. The next module covers what%ndoes to you.strlenreturningsize_tmeansstrlen(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,snprintfis the portable answer; its cost is formatting machinery you don't need for a plain copy, which is the only real argumentmemcpy+ explicit check wins.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Implementing UART on the ATmega328P
USART on the AtMega328P Needed Documentation * Arduino Nano PCB design * Atmega328P datasheet Materials used * Arduino Nano * Arduino Uno R3 * Relevant cable * Computer Software Used * make (for easy of compiling and building) * avr-gcc (our compiler for avr ISA) *…
Hello World, Embedded Edition: Blink an LED
Embedded C: Hello WorldNeeded DocumentationArduino Nano PCB designAtmega328P datasheetMaterials usedArduino NanoArduino Uno R3Relevant cableComputerSoftware Usedmake (for easy of compiling and building)avr-gcc (our compiler for avr ISA)binutils-avravr-libcavrdude (used to flash board)The…
Build Your Own Stack-Based Bytecode Virtual Machine in C
Ever wonder how Python's CPython, the JVM, or the Lua VM actually execute code under the hood? In this article, we build a stack-based bytecode virtual machine from scratch in C.
CPPFront Project is Aiming to Modernize the C++ Language
The highly vaunted C++ language would become simpler and safer under a proposal dubbed Cppfront, an experimental C++ front end being floated by prominent C++ developer Herb Sutter. Intended as a major C++ evolution, Cppfront is an experimental “syntax 1 to syntax 2” compiler designed to explore…