Re: Buffer overflow in "lpr"

Casper Dik (casper@HOLLAND.SUN.COM)
Tue, 08 Jul 1997 17:29:28 +0200

>strncat wouldn't do what you wanted in this case. It would append at
>most BUFSIZ characters, rather than at most BUFSIZE-strlen(buf)
>characters. Also, you need to '\0' terminate the buf after this
>because str*cat doesn't do that for you.

This is a common misconception about strncat().

Strncpy() and strncat() behave non-orthogonal.

strncpy(a, b, n): copy at most n characters from b to a; zerofil remainder.
NUL termination not guaranteed.
typical usage:

strncpy(a,b,sizeofa-1);
a[n-1] = '\0';

strncat(a,b,n): append at most n characters from b to a; then add NUL byte.

Typical usage:

strncat(a,b, sizeofa - strlen(a) - 1);

(It can be argued that atmost n bytes are appended to a, as the
trailing NUL byte of a is overwritten)

Yep, standards are that warped.

Casper