Vs c compilation error [error C4996: 'scanf': This function or variable may be unsafe.] solution, c4996unsafe
Compile a C-language project in VS. If the 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 a safer run-time library routines. The new Security CRT functions (that is, the functions with the suffix "_ s"), see:
Enhanced security of CRT Functions
The solution to this problem is as follows:
Method 1: replace the old function with the new Security CRT functions.
Method 2: Use the following method to block this warning:
1. Define the following macro in the pre-compiled header file stdafx. h (Note: Before you include any header files:
# Define _ CRT_SECURE_NO_DEPRECATE
2. Or Declaration# Param warning (disable: 4996)
3. modify the definition of preprocessing:
Project-> properties-> Configuration properties-> C/C ++-> pre-processor definition, add:
_ CRT_SECURE_NO_DEPRECATE
Method 3: method 2 does not use a safer CRT function. Obviously, it is not a recommended method, but we do not want to change the function name one by one. Here is a simpler method:
Define the following macro in the pre-compiled header file stdafx. h (before you include any header files:
# Define _ CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
The old function is automatically replaced with Security CRT functions at the link.
Note:: Although this method uses a new function, it cannot eliminate the warning (for the reason, see the red letter). You must also use method 2 (-_-). That is, the following two sentences should be added to the pre-compiled header file stdafx. h:
# Define _ CRT_SECURE_NO_DEPRECATE
# Define _ CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
Cause of error:
This kind of Microsoft warning is mainly caused by the C-library functions. Many functions do not perform parameter detection (including out-of-bounds functions). Microsoft is worried that using these functions will cause memory exceptions, therefore, the same function is rewritten, and the modified function is used for parameter detection. Using these new functions is more secure and convenient. You don't need to remember these rewrite functions, because the compiler will tell you the corresponding security function when giving a warning to each function. You can view the warning information, for more information, see MSDN.