RE: [PATCH net-next v1] hinic: fix strncpy output truncated compile warnings

From: David Laight
Date: Mon Aug 10 2020 - 04:15:55 EST


> Thanks for your explanation and review. I haven't realized using strncpy() on NUL-terminated strings
> is deprecated
> and just trying to avoid the compile warnings. The website you provide helps me a lot. Thank you very
> much!

Never try to remove compile-time warnings without understanding
what the code it doing.

The basic problem is that strncpy() almost [1] never does what you want.
It really expects it's input string to be '\0' terminated but
doesn't guarantee the output will be, and also (typically) wastes
cpu cycles zero filling the output buffer.

Someone then defined strscpy() as an alternative, it guarantees
to '\0' the output and doesn't zero fill - which can be an issue.
However strscpy() has it's own problems, the return value is
defined to be the length of the input string - which absolutely
requires it be '\0' terminated. With 'unknown' input this can
page fault!

[1] This fragment looked wrong, but was right!
strncpy(dest, src, sizeof src);
Naive conversion to remove the strncpy() broke it.
In fact 'dest' was 1 byte longer than 'src' and already
zero filled, 'src' might not have been '\0' terminated.
It is about the only time strncpy() is what you want!

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)