This week strncpy(3) was removed from the Linux kernel. It has a bad, and somewhat undeserved, reputation as a source of bugs and vulnerabilities.
If you’re not familiar with it, here’s what it looks like:
char * strncpy(char * dst, const char * src, size_t len);
You give it a destination space in memory, a source string, and a number of characters, and it copies source to destination up to the number of characters you specify. That’s it. In theory, what could be simpler? In practice, it’s a footgun.
If you’re not familiar, the C standard library has string functions which assume that strings are terminated by NULL. So if a string is “lowendbox” it’s stored as “lowendbox\0”. You don’t have to store it that way – in fact, you don’t have to use the standard library at all. Many projects create their own string library because C’s is 1970s-era thinking.
The strncpy library function assumes
- You have allocated space for the destination properly and successfully.
- The source string exists
- The size of the string is correctly counted
- You are accounting for the terminating \0
It’s that last couple one that bites people. They either overwrite something in memory (copying a 20-byte string to a 10-byte space), or they forget about the NULL. If you have “lowendbox” as a string, it’s easy to count “9 characters” but really it’s 10 because of that terminating NULL. Sure, in practice, you’d do a “sizeof(src)” but nevertheless, strncpy has a bad reputation.
But You Need the Lore Drop
strncpy() is very old. It first appeared in Version 7 AT&T UNIX, which was released in 1979. It was later standardized as part of ANSI C (C89).
A common misconception is that strncpy() was invented as a “safe” replacement for strcpy(). It wasn’t. Its original purpose was to handle fixed-width, null-padded fields such as filenames stored in directory entries and other on-disk structures. In that context:
- If the source string is shorter than the field width, the remainder of the field is padded with ‘\0’ bytes.
- If the source string is too long, it is truncated and may not be NUL-terminated.
This behavior makes sense for fixed-size records, but that isn’t how strncpy was later popularly used. People thought it was for safer strings. After all, strcpy(3) is:
char * strcpy(char * dst, const char * src);
There’s no size consideration there at all. You have to do that before on your own. So isn’t it safer to limit the number of bytes copied? I suppose you can make the case, but either way it’s still dangerous.
C is a fine language, but string-handling has never been one of its strengths. The idea of tossing around NULL-terminated sections of memory is a rather crude convention, which is why modern projects often use Glib or other string libraries.
strncpy is no more in Linux land, but please don’t spit on its grave. It did what it was designed to do.




















Leave a Reply