Re: strncpy clarify result may not be null terminated

Alejandro Colomar
2023-11-08T21:51:04Z

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

Hi DJ,

On Wed, Nov 08, 2023 at 04:07:07PM -0500, DJ Delorie wrote:
> Alejandro Colomar <alx@kernel.org> writes:
> > Would you mind reading the latest versions of strcpy(3), strncpy(3), and
> > string_copying(7), as in the git repository, and comment your thoughts?
>
> I think my examples would work well after the first CAVEATS paragaph:
>
> The name of these functions is confusing. These functions
> produce a null-padded character sequence, not a string (see
> string_copying(7)), like this:
>
> strncpy (buf, "1", 5) -> { '1', 0, 0, 0, 0 }
> strncpy (buf, "1234", 5) -> { '1', '2', '3', '4', 0 }
> strncpy (buf, "12345", 5) -> { '1', '2', '3', '4', '5' }
> strncpy (buf, "123456", 5) -> { '1', '2', '3', '4', '5' }

It fits perfectly there. And it also merges nicely with the paragraph
below.

>
> > These functions copy the string pointed to by src into a null-padded
> > character sequence at the fixed-width buffer pointed to by dst. If the
> > destination buffer, limited by its size, isn't large enough to hold the
> > copy, the resulting character sequence is truncated.
>
> hmmm... perhaps
>
> These functions copy at most SZ bytes from SRC into a fixed-length
> buffer DST, padding any unwritten bytes in DST with NUL bytes.
> Specifically, if SRC has a NUL byte in the first SZ bytes, copying
> stops there and any remaining bytes in DST are filled with NUL bytes.
> If there are no NUL bytes in the first SZ bytes of SRC, SZ bytes are
> copied to DST.
>
> This avoids the term "string" completely and emphasises the not-string
> nature of the destination.

I don't like that, because it talks a lot about what the function does
in terms of low-level copies of bytes. That may induce programmers to
try to find an abstraction in terms of strings.

>
> stpncpy, strncpy - zero a fixed-width buffer and copy a string into a
> character sequence with truncation and zero the rest of it
>
> Or "fill a fixed-width zero-padded buffer with bytes from a string"

But this wording is perfect! I also used a similar wording for the
description. I'll send a patch in a moment.

>
> That avoids saying "copy a string"

Yep!

>
> string_copying.7:
>
> > For historic reasons, some standard APIs, such as utmpx(5),
>
> Perhaps "some standard APIs and file formats,, such as utmpx(5) or
> tar(1)," ?

Yes; thanks!

>
> > however, those padding null bytes are not part of the character
> > sequence.
>
> add ", and may not be present if not needed." ?

I'm not convinced about this one. "needed" is not the right word I
think. For now, I'll add the other suggestions to a patch. Expect it
in a moment.

Cheers,
Alex

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