C4996(函数不安全)警告 strcpy 但不是 memcpy [英] C4996 (function unsafe) warning for strcpy but not for memcpy
问题描述
我正在 VS2010 中编写代码,我碰巧在编译器给我 C4996 警告(此函数或变量可能不安全")后看到 strcpy 和 sprintf 调用.
I am writing code in VS2010 and I happen to see after compilation compiler gives me C4996 warning ("This function or variable may be unsafe") for strcpy and sprintf calls.
但是,我无法收到类似的 memcpy 警告(并且代码中可能还有更多类似的不安全"函数调用)
However, I couldn't get similar warnings for memcpy (and may be there are few more similar 'unsafe' function calls in the code)
int _tmain(int argc, _TCHAR* argv[])
{
char buf1[100], buf2[100];
strcpy (buf1, buf2); // Warning C4996 displayed here asking to use strcpy_s instead
memcpy (buf1, buf2, 100); // No warning here asking to use memcpy_s
memcpy_s(buf1, 100, buf2, 100);
return 0;
}
为什么会这样?如何为代码中所有可能的不安全调用打开 C4996 警告?
Why is this so? How can I turn on C4996 warning for all possible unsafe calls in my code?
推荐答案
一般来说,要编译 C 代码,您需要一个符合标准的 C 编译器.Visual Studio 是不符合标准的 C++ 编译器.
In general, to compile C code you need a conforming C compiler. Visual Studio is a non-conforming C++ compiler.
您收到警告是因为 Visual Studio 很糟糕.见此.
You get the warning because Visual Studio is bad. See this.
C4996 在您使用 Microsoft 认为已过时的功能时出现.显然,微软已经决定他们应该决定 C 语言的未来,而不是 ISO C 工作组.因此,对于完美的代码,您会收到错误警告.编译器有问题.
C4996 appears whenever you use a function that Microsoft regards as obsolete. Apparently, Microsoft has decided that they should dictate the future of the C language, rather than the ISO C working group. Thus you get false warnings for perfectly fine code. The compiler is the problem.
strcpy() 函数没有任何问题,这是一个神话.这个功能已经存在了大约 30 到 40 年,它的每一点都被适当地记录下来.因此,即使对于 C 初学者来说,该函数能做什么和不能做什么都不应该感到惊讶.
There is nothing wrong with the strcpy() function, that's a myth. This function has existed for some 30-40 years and every little bit of it is properly documented. So what the function does and what it does not should not come as a surprise, even to beginner C programmers.
strcpy 做什么和不做什么:
What strcpy does and does not:
- 它将一个以空字符结尾的字符串复制到另一个内存位置.
- 它对错误处理不承担任何责任.
- 它不会修复调用方应用程序中的错误.
- 它不承担任何教育 C 程序员的责任.
由于上面的最后一句话,调用strcpy之前你必须知道以下几点:
Because of the last remark above, you must know the following before calling strcpy:
- 如果您将未知长度的字符串传递给 strcpy,而没有提前检查其长度,那么您的调用方应用程序就会出现错误.
- 如果您传递一些不以