C strcpy() - evil?

前端 未结 17 1392
梦毁少年i
梦毁少年i 2020-12-23 10:50

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

17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 11:08

    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 use strncpy() 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 and strlcat 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.

提交回复
热议问题