tech-kern archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: Usage of strncpy in the kernel



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



Home | Main Index | Thread Index | Old Index