Hi, On 12/4/22 21:42, Alejandro Colomar wrote: > As an unrelated note.  I've had this running in my mind for some time... your > various bug reports for strncpy(3) and similar wide character functions have > triggered those thougts. > > I'm going to mark strncpy(3) and similar functions as deprecated, even if no > libc or standard has done so.  There's wide agreement (at least in some > communities) that strncpy(3) _is evil_.  There's simply no use for it. > > I propose that glibc also marks it as deprecated. > > I've worked for a few months on improving string handling in various projects: > shadow-utils , and in nginx > Unit.  I've come to the following guidelines for using strings: > > -  strlcpy(3):  Copy from string to string, detecting truncation > -  strscpy(9):  Copy from untrusted string to string, detecting broken ones > -  ustr2str():  Copy from unterminated string to string >    -  Definition: > > > -  stpecpy():  Copy from string to string, with easy & safe concatenation, and > reporting truncation at the end of the chain call. >    -  Definition: > > > -  ustr2stpe():  Combination of ustr2str() and stpecpy(). >    -  Definition:  Not yet public > > > And also, memcpy(), mempcpy(), or memccpy() can be used for copying unterminated > strings. > > But I don't see any scenario where strncpy() is the right function to call.  And > the name is certainly not telling that either. I did some initial work, to split strcpy(3) and strncpy(3) manual pages, and clearly document the only purpose for which strncpy(3) seems to be useful (or at least, not plain wrong): copying a string into a fixed-width buffer, and ensuring that no garbage is leaked. However, even for that niche use-case, it has issues: it can't report truncation. Consider a trivial implementation of strncpy(3): char * strncpy(char *dest, const char *src, size_t n) { bzero(dest, n); memccpy(dest, src, '\0', n); return dest; } As this implementation hints, this function is only useful when you do want to apply those two calls in that order. There are few use cases for that, but not inexistent, okay. However: (1) Having the 2 separate calls is probably better for self documentation than strncpy(3), especially since strncpy(3) has been misused extensively. However, if a project correctly documents its use of strncpy(3), it might be fine, and less code. (2) strncpy(3) can't detect truncation. strncpy(3) has been misdesigned, and this repurpose is not great. (3) Its name is not at all telling what it does. Which is why I think we should deprecate it. Cheers, Alex --