Re: Usage of strncpy in the kernel

Roland Illig <[email protected]>
Newsgroups gmane.os.netbsd.devel.kernel
Message-ID <[email protected]>
Am 03.01.2025 um 14:37 schrieb Mouse:
>> I stumbled across a few usages of strncpy in the kernel [...]
>
>>> strlcpy(name, "... preferred name ...", sizeof(sc->sc_sensor.desc));
> [...]
>>> strlcpy(sc->sc_sensor.desc, name, sizeof(sc->sc_sensor.desc));
>
> Um, strlcpy != strncpy.  Are you counting strlcpy as a variant of
> strncpy for purposes of this suggestion?

No, strlcpy is fine for string handling, as it expects (null-terminated)
strings and also produces them.

It's only strncpy (and probably strncat) that are problematic, as these
two are hard to use correctly for handling strings.

>> These code snippets made me wonder whether strncpy should be banned
>> from kernel code, in order to force developers to think about
>> properly handling character arrays and strings.
>
> But what would you use, then, to copy a string?

I would use strlcpy or snprintf, or even strcpy if the length of the
source string is known.

Roland
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.