3 ms·
Use strlcpy/strlcat instead.[0] strlcpy takes the full size of the destination buffer, limits the copy to N-1, and nul-terminates the result for you. It's lik
by loeg 8y ago
Use strlcpy/strlcat instead.[0] strlcpy takes the full size of the destination buffer, limits the copy to N-1, and nul-terminates the result for you. It's like the "correct" example in TFA, but with less annoying boilerplate.
Some more verbose design/rationale for the really curious.[1]
Another thing to keep in mind is the sometimes surprising behavior of strncpy(large_buffer, short_string, sizeof(large_buffer))[2]:
If the length of src is less than n, strncpy() writes additional null
bytes to dest to ensure that a total of n bytes are written.
Strlcpy doesn't do that. Just use strlcpy. On Linux, it can be found in the libbsd package.
[0]: https://www.freebsd.org/cgi/man.cgi?query=strlcpy&sektion=3 https://www.freebsd.org/cgi/man.cgi?query=strlcpy&sektion=3
[1]: https://www.sudo.ws/todd/papers/strlcpy.html https://www.sudo.ws/todd/papers/strlcpy.html
[2]: https://linux.die.net/man/3/strncpy https://linux.die.net/man/3/strncpy