On 04/11/2023 19:33, Alejandro Colomar wrote: > Hi Jonny, > > On Sat, Nov 04, 2023 at 11:27:44AM +0000, Jonny Grant wrote: >> Hello >> I have a suggestion for strncpy. >> >> C23 draft states this caveat for strncpy. >> >> "373) Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null- >> terminated." >> >> >> https://man7.org/linux/man-pages/man3/strncpy.3.html >> >> "If the destination buffer, limited by its size, isn't large >> enough to hold the copy, the resulting character sequence is >> truncated. " > > The use of the term "character sequence" instead of "string" isn't > casual. A "string" is a sequence of zero or more non-zero characters, > followed by exactly one NUL. A "character sequence" is a sequence of > zero or more non-zero characters, period. > > To be clearer in that regard, the CAVEATS section of the same page says > this: > > CAVEATS > The name of these functions is confusing. These functions pro‐ > duce a null‐padded character sequence, not a string (see > string_copying(7)). > > Saying that these functions don't produce a string should warn anyone > thinking it would. The page string_copying(7) goes into more detail. > >> >> How about clarifying this as: >> >> >> "If the destination buffer, limited by its size, isn't large >> enough to hold the copy, the resulting character sequence is >> truncated; where there is no null terminating byte in the first n >> characters the result will not be null terminated. " > > strncpy(3) should !*NEVER*! be used to produce a string. > I don't think that should be conditional. Your suggested change could > induce to the mistake of thinking that strncpy(3) is useful if the size > of the buffer is enough. Do not ever use that function for producing > strings. Use something else, like strlcpy(3), strcpy(3), or stpecpy(3). > > Cheers, > Alex > >> >> Kind regards, Jonny Michael, what do you think about this documentation suggestion I have made. Interested to hear your opinion. Should the man page follow the C spec description of the strncpy function and how when it copies the arrays, it may leave the resulting array of characters not terminated, and warn about this pitfall. C99 had this, and it is still there in latest C23 draft - worth clarifying on strncpy(3)? "7.21.2.4 The strncpy function" "269) Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null-terminated." Note, I'm not using strncpy myself, it's a documentation clarification proposal. Kind regards Jonny