strcpy.3: Fix example code for strncpy, which could pass an incorrect length

The example code currently passes `buflen - 1` to `strncpy`,
however the length parameter to `strncpy` is `size_t`, which is
unsigned.  This means that when `buflen` is zero, the cast of `-1`
to unsigned will result in passing `UINT_MAX` as the length.
Obviously, that would be incorrect and could cause `strncpy` to
write well beyond the buffer passed.

The easy solution is to wrap the whole code in the `buflen > 0`
check, rather then just the part of the code that applies the null
terminator.

Signed-off-by: Matthew Kilgore <mattkilgore12@gmail.com>
Signed-off-by: Michael Kerrisk <mtk.manpages@gmail.com>
This commit is contained in:
Matthew Kilgore 2018-06-07 00:10:51 -04:00 committed by Michael Kerrisk
parent 4c974cbac6
commit 85bbb2a253
1 changed files with 3 additions and 2 deletions

View File

@ -166,9 +166,10 @@ you can force termination using something like the following:
.PP
.in +4n
.EX
strncpy(buf, str, buflen \- 1);
if (buflen > 0)
if (buflen > 0) {
strncpy(buf, str, buflen \- 1);
buf[buflen \- 1]= \(aq\\0\(aq;
}
.EE
.in
.PP