Re: strncpy clarify result may not be null terminated

Alejandro Colomar
2023-11-04T19:34:00Z

[-- Attachment #1: Type: text/plain, Size: 1940 bytes --]

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

--
<https://www.alejandro-colomar.es/>