Re:Strlcpy and Strlcat – Consistent, Safe, String Copy and C...
by pajko on Tuesday April 25, 2023 @09:41AM
(#35700325)
Except snprintf() does not terminate the string if there's no room for the final \0. So technically this should be
snprintf(buf, sizeof buf - 1, "%s%s", "foo", "bar");
buf[sizeof buf - 1] = '\0';
[ Parent
| on HN ]
Re:Strlcpy and Strlcat – Consistent, Safe, String Copy and C...
by q3k on Tuesday April 25, 2023 @10:00AM
(#35700595)
Check the return value! Unless you really want truncated values, but I would assume most people don't.
Re:Strlcpy and Strlcat – Consistent, Safe, String Copy and C...
by unwind on Tuesday April 25, 2023 @03:24PM
(#35705380)
I don't think that is correct, my understanding is that it always terminates when possible. FreeBSD's man page [1] has a pretty clear description:
The snprintf() and vsnprintf() functions will write at most size-1 of the characters printed into the output string (the size'th character then gets the terminating `\0'); if the return value is greater than or equal to the size argument, the string was too short and some of the printed characters were discarded. The output is always null-terminated, unless size is 0.
On a more anecdotal front, I did a quick test on Ideone [2] that seems to behave exactly how I would expect it to (and contradicts your description).
In short: always call snprintf() with the exact size of the buffer. No Obi-Wans.