Comment by ahoka
1 day ago
"strncpy() is a weird function with a crappy API."
Well if you bother looking up that it's originally created for non null-terminated strings, then it kinda makes sense.
The real problem begun when static analyzers started to recommend using it instead of strcpy (the real alternative used to be snprintf, now strlcpy).
strlcpy is a BSD-ism that isn't in posix. The official recommendation is stpecpy. Unfortunately, it is only implemented in the documentation, but not available anywhere unless you roll your own:
https://man7.org/linux/man-pages/man7/string_copying.7.html
strlcpy is in POSIX now, actually.
https://pubs.opengroup.org/onlinepubs/9799919799/functions/s...
Ah, good point. I forgot it had just gotten added. Past context https://news.ycombinator.com/item?id=36765747
Who cares? Just vendor it into your project. It's a tiny string manipulation function.
(I agree with the author of the piece that strlcpy doesn't actually solve the real problem.)
Your comment makes no sense. If it was designed for non-null terminated strings, why would it specifically pad after a null terminator?
I looked up the actual reason for its inception:
---
> If it was designed for non-null terminated strings, why would it specifically pad after a null terminator?
Padded and terminated strings are completely different beasts. And the text you quote tells you black on white that strncpy deals in padded strings.
“fixed-length name fields in structures such as directory entries”
“the trailing null is unnecessary for a maximum-length field”
That is a non–null terminated string.