"strcpy"和"strcpy_s"之间的区别?
Difference between 'strcpy' and 'strcpy_s'?
当我尝试使用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
和strcpy_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就会像任何其他编译器一样工作。
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 使用strcpy将char数组的元素复制到另一个数组
- int(c) 和 c-'0' 之间的区别。C++
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- C++ - "!pointer"和"pointer == nullptr"的区别?
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 返回递归调用和仅递归调用的区别
- Qt:remove() 和 rmdir() 有什么区别
- 这 4 个 lambda 表达式之间有什么区别?
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- (double) 和 double() 之间的区别
- 将向量作为类>(值)<向量启动和向量<类>[值]有什么区别
- 分配指针和使用strcpy之间的区别
- "strcpy"和"strcpy_s"之间的区别?