Some people seem to think that C\'s strcpy()
function is bad or evil. While I admit that it\'s usually better to use strncpy()
in order to avoid bu
No one has mentioned strlcpy, developed by Todd C. Miller and Theo de Raadt. As they say in their paper:
The most common misconception is that
strncpy()
NUL-terminates the destination string. This is only true, however, if length of the source string is less than the size parameter. This can be problematic when copying user input that may be of arbitrary length into a fixed size buffer. The safest way to usestrncpy()
in this situation is to pass it one less than the size of the destination string, and then terminate the string by hand. That way you are guaranteed to always have a NUL-terminated destination string.
There are counter-arguments for the use of strlcpy
; the Wikipedia page makes note that
Drepper argues that
strlcpy
andstrlcat
make truncation errors easier for a programmer to ignore and thus can introduce more bugs than they remove.*
However, I believe that this just forces people that know what they're doing to add a manual NULL termination, in addition to a manual adjustment to the argument to strncpy
. Use of strlcpy
makes it much easier to avoid buffer overruns because you failed to NULL terminate your buffer.
Also note that the lack of strlcpy
in glibc or Microsoft's libraries should not be a barrier to use; you can find the source for strlcpy
and friends in any BSD distribution, and the license is likely friendly to your commercial/non-commercial project. See the comment at the top of strlcpy.c
.