Why does strncpy not null terminate?

Originally, the 7th Edition UNIX file system (see DIR(5)) had directory entries that limited file names to 14 bytes; each entry in a directory consisted of 2 bytes for the inode number plus 14 bytes for the name, null padded to 14 characters, but not necessarily null-terminated. It's my belief that strncpy() was designed to work with those directory structures - or, at least, it works perfectly for that structure.

Consider:

  • A 14 character file name was not null terminated.
  • If the name was shorter than 14 bytes, it was null padded to full length (14 bytes).

This is exactly what would be achieved by:

strncpy(inode->d_name, filename, 14);

So, strncpy() was ideally fitted to its original niche application. It was only coincidentally about preventing overflows of null-terminated strings.

(Note that null padding up to the length 14 is not a serious overhead - if the length of the buffer is 4 KB and all you want is to safely copy 20 characters into it, then the extra 4075 nulls is serious overkill, and can easily lead to quadratic behaviour if you are repeatedly adding material to a long buffer.)


strncpy() is not intended to be used as a safer strcpy(), it is supposed to be used to insert one string in the middle of another.

All those "safe" string handling functions such as snprintf() and vsnprintf() are fixes that have been added in later standards to mitigate buffer overflow exploits etc.

Wikipedia mentions strncat() as an alternative to writing your own safe strncpy():

*dst = '\0';
strncat(dst, src, LEN);

EDIT

I missed that strncat() exceeds LEN characters when null terminating the string if it is longer or equal to LEN char's.

Anyway, the point of using strncat() instead of any homegrown solution such as memcpy(..., strlen(...))/whatever is that the implementation of strncat() might be target/platform optimized in the library.

Of course you need to check that dst holds at least the nullchar, so the correct use of strncat() would be something like:

if (LEN) {
    *dst = '\0'; strncat(dst, src, LEN-1);
}

I also admit that strncpy() is not very useful for copying a substring into another string, if the src is shorter than n char's, the destination string will be truncated.


There are already open source implementations like strlcpy that do safe copying.

http://en.wikipedia.org/wiki/Strlcpy

In the references there are links to the sources.

Tags:

C

Strncpy