Visual Studio 2012 error C4996: ‘scanf’: This function or variable may be unsafe.

When compiling C language projects in vs 2012, if scanf function is used, the following error will be prompted during compilation:

error C4996: ‘scanf’: This function or variable may be unsafe. Consider using scanf_ s instead. To disable deprecation, use _ CRT_ SECURE_ NO_ WARNINGS. See online help for details.

The reason is that visual c + + 2012 uses more secure run time library routines. New security CRT functions_ S “suffix), see:

Security enhanced version of CRT function

Here is a solution to this problem

Method 1: replace the old function with the new security CRT functions.

Method 2: use the following methods to block this warning:

1. Define the following macro in the precompiled header file StdAfx. H

#define _ CRT_ SECURE_ NO_ DEPRECATE

2. Or declare “param warning”( disable:4996 )

3. Change the definition of preprocessing

Project – & gt; properties – & gt; configuration properties – & gt; C/C + + – & gt; preprocessor – & gt; preprocessor definition, add:

_ CRT_ SECURE_ NO_ DEPRECATE

Method 3: Method 2 does not use a more secure CRT function, which is obviously not a good recommended method. However, we do not want to change the function names one by one. Here is a simpler method:

In the precompiled header file StdAfx. H (also before any header file is included), define the following macro:

#define _ CRT_ SECURE_ CPP_ OVERLOAD_ STANDARD_ NAMES 1

When linking, the old function will be automatically replaced with security CRT functions.

Note: Although this method uses a new function, it can’t eliminate the warning (see the red letter for the reason). You have to use method 2 (-_ -)。 In fact, the following two sentences should be added to the precompiled header file StdAfx. H:

#define _ CRT_ SECURE_ NO_ DEPRECATE

#define _ CRT_ SECURE_ CPP_ OVERLOAD_ STANDARD_ NAMES 1


Error reason explanation:

This kind of Microsoft’s warning is mainly due to the fact that many functions in the C library do not carry out parameter detection (including cross-border functions). Microsoft is worried that using these functions will cause memory exceptions, so it rewrites the functions with the same functions, and the rewritten functions carry out parameter detection. It will be safer and more convenient to use these new functions. You don’t need to memorize these rewritten functions, because the compiler will tell you the corresponding security function when it gives a warning for each function. You can get it by checking the warning information, and check MSDN for details when you use it.

Read More: