3 ms·
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
by pajko 3y ago
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';
- q3k 3y agoCheck the return value! Unless you really want truncated values, but I would assume most people don't.
- unwind 3y agoI 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. [1]: https://man.freebsd.org/cgi/man.cgi?query=snprintf https://man.freebsd.org/cgi/man.cgi?query=snprintf [2]: https://ideone.com/CdLfNS https://ideone.com/CdLfNS
- deleted 3y ago[deleted]