At Sat, 4 Jan 2025 10:14:09 +0000, David Holland <dholland-tech%netbsd.org@localhost> wrote: Subject: Re: Usage of strncpy in the kernel > > 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. Hmmm... strlcpy() being the unique oddity, and a recent invention.... I would think an experienced C programmer should know (without ever having to look at the manual page), that manually terminating the destination array after strncpy() is idiomatic (assuming one wants the destination to be used as a "string"). strncpy() has the advantage of working nicely and predictably regardless of whether the known buffer's length is that of the source or that of the destination. I.e. one can use it to copy a known number of possibly (or definitely) unterminated chars from an array of a given length into an array of the same or larger size; or one can use it to copy a string of unknown length into into a fixed length array (that can then be terminated to for a truncated copy of the original string). I'd guess it is this dual use that can sometimes confuse people, though good naming of the variables passed as arguments should avoid any confusion. Either way if the result is to be called a "string" then it must be NUL-terminated (and of course the destination array must be one char larger than the desired string length in order to accommodate the NUL). The "str" part of its name basically just tells us it treats the source as a string -- otherwise we would use memcpy(). To me I find strlcpy() to be basically useless. It's not standard (i.e. outside of kernel space), and it doesn't offer enough new functionality to be interesting, and it's not flexible enough. It CANNOT replace strncpy(). > 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); I definitely don't like those names -- the 'l' should not be in there for starters -- an 'n' would make more sense if anything! I'm not sure they're very useful over and above the existing strncpy(), though I do agree that they may help inexperienced programmers who forget about doing NUL termination where necessary. On the other hand, if one desires a new API with some form of better "safety", perhaps one should look no further than C11's new str*_s() functions. But note they change the API of their namesakes drastically and require their return values be checked for error indications instead. -- Greg A. Woods <gwoods%acm.org@localhost> Kelowna, BC +1 250 762-7675 RoboHack <woods%robohack.ca@localhost> Planix, Inc. <woods%planix.com@localhost> Avoncote Farms <woods%avoncote.ca@localhost>
Attachment:
pgpwaWQIJErsC.pgp
Description: OpenPGP Digital Signature