Re: strncpy clarify result may not be null terminated

DJ Delorie
2023-11-08T21:08:01Z

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' }

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

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"

That avoids saying "copy a string"

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)," ?

> however, those padding null bytes are not part of the character
> sequence.

add ", and may not be present if not needed." ?