Why is strcpy unsafe in C? [duplicate]

↘锁芯ラ 提交于 2019-12-01 17:59:48

strcpy has no way of knowing how large the destination buffer is (i.e. there is no length parameter) so sloppy programming using it can lead to overrunning the buffer and corrupting other memory. Such an overrun can lead to crashes, odd behaviour and may be exploitable by malware authors.

BTW, look at strncpy that takes a length parameter. One problem to be aware of is that strncpy will not terminate the string if the buffer is too small so it is dangerous in its own way.

In answer to your comment/question - it will depend on context. If you know the buffer is large enough (for example, you allocated it in the previous line at the correct size), use strcpy. If there is any possibility of an overflow then use strncpy and make sure you set the last position in the buffer to null. Note that "any possibility" should be interpreted very generously - unless the previous five or six lines are enough to show safety then use strncpy.

Also see Andon's comment above about strncpy_s. Finally, if you do use strcpy, you might want to add a #pragma to suppress the warning at that location.

Here's your original code:

int main() {
    char str1[] = "Copy a string.";
    char str2[15];

    strcpy(str2, str1);
}

Now, three day later, you go to edit this code. You've realized that you actually need to write the message "This code is copying a string." instead.

int main() {
    char str1[] = "This code is copying a string.";
    char str2[15];

    strcpy(str2, str1);
}

However, you've now accidentally introduced a buffer overflow.

strcpy_s requires the extra argument of the length of str2. This way, while you may not get the whole string into your new buffer, you won't cause undefined behavior.

Unlike strncpy and strcpy_s, strcpy doesn't do any length checking of the destination buffer which may cause stack overflow allowing an attacker to execute malicious code if exploited or just crach your application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!