[Swan] strncpy doesn't do what many people think that it does

D. Hugh Redelmeier hugh at mimosa.com
Fri Feb 15 05:47:38 EET 2013


SYNOPSIS
	char *strncpy(char *dest, const char *src, size_t n);

DESCRIPTION

       	The strncpy() function is similar [to strcpy], except that at
	most n bytes of src are copied.  Warning: If there is no null
	byte among the first n bytes of src, the string placed in dest
	will not be null-terminated.

That means that strncpy is not a complete or safe or sensible way of
truncating a C string.  It is useful for other purposes.

Not complete: it won't ensure a final NUL.

Not safe: it won't ensure a final NUL.

Not sensible:

- generally, silent truncation is unfriendly.  Truncation is a sign of
  a problem that should be reported.

- most strings are way shorter than the bound.  What a waste to fill
  the unused space with NULs

void
silent_tuncating_strcpy(char *dest, const char *src, size_t n)
{
	size_t len = strlen(src);

	assert(n != 0);		/* won't hold a string! */
	if (len >= n)
		len = n-1;
	memcpy(dest, src, len);
	dest[len] = '\0';
}

libreswan contains at least one example of this mistake.
Let the easter egg hunt begin!

(Thanks to Coverity for flagging this.)


More information about the Swan mailing list