Re: strncpy clarify result may not be null terminated

Alejandro Colomar
2023-11-08T19:40:23Z

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

Hi DJ,

On Wed, Nov 08, 2023 at 02:04:45PM -0500, DJ Delorie wrote:
> Alejandro Colomar <alx@kernel.org> writes:
> > strncpy(3) is useful to write to fixed-width buffers like `struct utmp`
> > and `struct utmpx`. Is there any other libc API that needs strncpy(3)?
>
> Let's not limit ourselves to glibc APIs. Tar format, for example, uses
> fixed length fields (and my bet is that strncpy was created for it) yet
> tar is not part of glibc.
>
> IMHO the solution here is to document strncpy with sufficiently obvious
> intent that it is NOT a length-limited strcpy (i.e. strlcpy) and should
> ONLY be used for its intended purpose (filling a space-padded but not
> null-terminated field)

Indeed. That's what I did (I think).

DESCRIPTION
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.

...

CAVEATS
The name of these functions is confusing. These functions pro‐
duce a null‐padded character sequence, not a string (see
string_copying(7)).

It’s impossible to distinguish truncation by the result of the
call, from a character sequence that just fits the destination
buffer; truncation should be detected by comparing the length of
the input string with the size of the destination buffer.

I refuse to add any hints that strncpy(3) is good for copying strings.

>
> It is not documentation's purpose to limit programmer's creativity, just
> to give them an accurate representation of what the functions do.

Thanks!

Cheers,
Alex

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