"strcpy"和"strcpy_s"之间的区别?

Difference between 'strcpy' and 'strcpy_s'?

本文关键字:strcpy 区别 之间      更新时间:2023-10-16

当我尝试使用strcpy复制字符串时,它给了我一个编译错误。

error C4996 'strcpy': This function or variable may be unsafe.
 
Consider using `strcpy_s` instead. To disable deprecation, 
use `_CRT_SECURE_NO_WARNINGS`. See online help for details.

strcpystrcpy_s的区别是什么?

strcpy是一个不安全函数。当你试图使用strcpy()将一个字符串复制到一个不够大的缓冲区时,它将导致缓冲区溢出。

strcpy_s()strcpy()安全增强版本。使用strcpy_s,您可以指定目标缓冲区的大小,以避免在复制期间缓冲区溢出。

char tuna[5];  // a buffer which holds 5 chars incluing the null character.
char salmon[] = "A string which is longer than 5 chars";
strcpy( tuna, salmon ); // This will corrupt your memory because of the buffer overflow.
strcpy_s( tuna, 5, salmon ); // strcpy_s will not write more than 5 chars.

我想补充一点,如果你试图编译别人的代码,MS总是会抱怨标准库中的不安全函数。只要像错误消息告诉您的那样定义_CRT_SECURE_NO_WARNINGS, MSVC就会像任何其他编译器一样工作。