tech-kern archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
Re: Usage of strncpy in the kernel
On Sat, Jan 04, 2025 at 03:25:20AM +0100, Johnny Billquist wrote:
> Well, as for using strncpy to read out strings from memory as described
> below, it is really trivial to get it right, using strncpy, so I don't
> really agree with that it should be banned. But people need to do things
> right.
>
> But just the following solves it nicely, with very little headaches.
>
> char buf[8];
> strncpy(sizeof(buf), dst, buf);
> buf[sizeof(buf)-1] = 0;
That both has the arguments in the wrong order and doesn't entirely
make sense (did you mean src instead of dst? Or did you mean to
null-terminate dst?)
However, no matter how you patch it up it still doesn't terminate the
output unless you remember to, which is a common problem when people
try to use strncpy as a substitute for strlcpy. Then, if you meant
strncpy(dst, buf, sizeof(buf)), it doesn't crosscheck the length of
dst and also throws away the last byte of the data, and if you meant
strncpy(buf, src, sizeof(buf)) it doesn't check the length of src and
will run off the end if the size of buf is too large.
Which is exactly why there should be a function for this :-)
maybe something like
strlcpy_tofixed(char *dest, size_t destlen, const char *src);
strlcpy_fromfixed(char *dest, size_t destmax, const char *src, size_t srclen);
and
strlcpy_zerofill(char *dest, const char *src, size_t destmax);
--
David A. Holland
dholland%netbsd.org@localhost
Home |
Main Index |
Thread Index |
Old Index