为什么MSVC ++认为“std :: strcat”是“不安全的”? (C ++) [英] Why does MSVC++ consider "std::strcat" to be "unsafe"? (C++)
问题描述
当我尝试这样做:
char* prefix = "Sector_Data\\sector";
char* s_num = "0";
std::strcat(prefix, s_num);
std::strcat(prefix, "\\");
等等,我收到警告
warning C4996: 'strcat': This function or variable may be unsafe. Consider using strcat_s instead.
为什么strcat被认为不安全,有没有办法摆脱这个警告,而不使用strcat_s?
Why is strcat considered unsafe, and is there a way to get rid of this warning without using strcat_s?
此外,如果摆脱警告的唯一方法是使用strcat_s,它是如何工作的(语法明确:显然它不接受两个参数)。
Also, if the only way to get rid of the warning is to use strcat_s, how does it work (syntax-wise: apparently it does not take two arguments).
推荐答案
因为缓冲区前缀可能比复制到缓冲区的空间少,导致缓冲区溢出。
因此,黑客可以传入一个特殊的字符串,覆盖返回地址或其他关键内存,并在程序的上下文中开始执行代码。
Because the buffer, prefix, could have less space than you are copying into it, causing a buffer overrun. Therefore, a hacker could pass in a specially crafted string which overwrites the return address or other critical memory and start executing code in the context of your program.
strcat_s通过强制您传递要复制字符串的缓冲区的长度来解决此问题;如果有必要,它将截断字符串,以确保缓冲区不会超限。
strcat_s solves this by forcing you to pass in the length of the buffer into which you are copying the string; it will truncate the string if necessary to make sure that the buffer is not overrun.
google strcat_s以准确地查看如何使用它。
google strcat_s to see precisely how to use it.
这篇关于为什么MSVC ++认为“std :: strcat”是“不安全的”? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!