Re: strncpy clarify result may not be null terminated

Paul Eggert
2023-11-09T18:11:13Z

On 2023-11-09 03:38, Alejandro Colomar wrote:
> If you are consistent in checking the return value of strlcpy(3) and
> reporting an error, it's the best standard alternative nowadays.

Not necessarily. strlcpy is subject to denial-of-service attacks if the
attacker has control of the source string and can attack by using long
source strings. strncpy, as bad as it is, does not have this problem.

Instead of this:

if (strlcpy (dst, src, dstsize) == dstsize)
return failure;

applications that want want to copy a string into a small nonempty
fixed-size buffer, failing if the string doesn't fit, should do
something like this:

if (strncpy (dst, src, dstsize)[dstsize - 1])
return failure;

This avoids the denial-of-service attack and is portable all the way
back to K&R C.

It's unfortunate that strlcpy was misdesigned but here we are.