Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C4996 (function unsafe) warning for strcpy but not for memcpy

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.

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;
}

Why is this so? How can I turn on C4996 warning for all possible unsafe calls in my code?

like image 684
Atul Avatar asked Nov 27 '22 09:11

Atul


1 Answers

In general, to compile C code you need a conforming C compiler. Visual Studio is a non-conforming C++ compiler.

You get the warning because Visual Studio is bad. See this.

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.

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.

What strcpy does and does not:

  • It copies a null-terminated string into another memory location.
  • It does not take any responsibility for error handling.
  • It does not fix bugs in the caller application.
  • It does not take any responsibility for educating C programmers.

Because of the last remark above, you must know the following before calling strcpy:

  • If you pass a string of unknown length to strcpy, without checking its length in advance, you have a bug in the caller application.
  • If you pass some chunk of data which does not end with \0, you have a bug in the caller application.
  • If you pass two pointers to strcpy(), which point at memory locations that overlap, you invoke undefined behavior. Meaning you have a bug in the caller application.

For example, in the code you posted, you never initialized the arrays, so your program will likely crash and burn. That bug isn't in the slightest related to the strcpy() function and will not be solved by swapping out strcpy() for something else.

like image 164
Lundin Avatar answered Dec 09 '22 13:12

Lundin