C++ “strcpy”和“strcpy_s”之间的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32136185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between 'strcpy' and 'strcpy_s'?
提问by Bluebaby
When i tries to use strcpy
to copy a string it gave me a compile error.
当我尝试使用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.
考虑strcpy_s
改用。要禁用弃用,请使用_CRT_SECURE_NO_WARNINGS
. 详细信息请参见在线帮助。
What is the difference between strcpy
and strcpy_s
?
strcpy
和 和有strcpy_s
什么区别?
回答by Deadlock
strcpy is a unsafe funtion. When you try to copy a string using strcpy(), to a buffer which is not large enough to contain it, it will cause a buffer overflow.
strcpy 是一个不安全的函数。当您尝试使用 strcpy() 将字符串复制到不足以容纳它的缓冲区时,会导致缓冲区溢出。
strcpy_s() is a security enhanced versionof strcpy(). With strcpy_s you can specify the size of the destination buffer to avoid buffer overflows during copies.
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.
回答by Navin
I'd like to add that if you ever try to compile other people's code, MS will always complain about unsafe functions in the standard library. Just define _CRT_SECURE_NO_WARNINGS
like the error message tells you to and MSVC will work like any other compiler.
我想补充一点,如果您尝试编译其他人的代码,MS 总是会抱怨标准库中的函数不安全。只需_CRT_SECURE_NO_WARNINGS
像错误消息告诉您的那样定义,MSVC 将像任何其他编译器一样工作。