Re: strncpy clarify result may not be null terminated

Jonny Grant
2023-11-20T23:09:01Z

On 20/11/2023 15:12, Alejandro Colomar wrote:
> Hi Jonny,
>
> On Mon, Nov 20, 2023 at 11:56:40AM +0000, Jonny Grant wrote:
>> BTW, GCC has a useful warning for truncation that may help code bases that use strncpy, you've probably seen this and the article, just sharing for completeness.
>
> It's actually the opposite. GCC's warnings about strncpy(3) are
> nefarious, as it warns in valid uses of strncpy(3) for writing a
> null-padded character sequence (the use for which strncpy(3) was
> designed), recommending the bogus use as a function for copying
> truncated strings.

You're right, I can see this warning is issued for valid uses of strncpy(3) to copy a sequence of characters, (without even a single NUL pad). It does not warn when the byte sequence count includes a NUL byte.

>>
>> warning: ‘__builtin_strncpy’ output truncated before terminating nul copying XYZ bytes from a string of the same length [-Wstringop-truncation]
>>
>>
>> Martin's article from 2019
>> https://developers.redhat.com/blog/2018/05/24/detecting-string-truncation-with-gcc-8#forming_truncated_strings_with_snprintf
>
> I discussed with Martin about this, IIRC, and he told me they had to
> decide which use of strncpy(3) to support, with the side effect that
> other uses would be warned about, and they chose the one that I think is
> bogus.

Fair enough.

While I remember, the strlcpy discussion has been going on for over 20 years.

https://sourceware.org/legacy-ml/libc-alpha/2000-08/msg00053.html

https://news.ycombinator.com/item?id=6940601

Kind regards, Jonny