C language Miscellaneous (1) scanf (), scanf_s () and errors C4996, scanf_sc4996
Error C4996
When I was a beginner at C language, the first I/O function that I/O came into contact was scanf. However, when compiling code in Visual Studio (including but not limited to 2015, 2013, and 2012) in a later version, unexpected errors may occur.
There is a simple piece of code as follows:
#include "stdio.h"int main(void){ int i; printf("Input i\n"); scanf("%d", &i); printf("i is %d", i); return 0;}
However, an error C4996 is output, and the error message is as follows:
Error 1 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.
It is recommended that scanf be replaced by scanf_s. After replacement, the Code is as follows:
#include "stdio.h"int main(void){ int i; printf("Input i\n"); scanf_s("%d", &i); printf("i is %d", i); return 0;}
No error message is displayed.
Scanf and scanf_s
In MSDN, we have introduced these functions ending with _ s, including scanf_s, scanf_s_l, wscanf_s, and _ wscanf_s_l. Functions of these versions have enhanced security.
Functions such as scanf exist in the older version of CRT (C runtime library, part of the C standard library) and have security issues. For example, when reading characters, if the width of % s is not specified, the buffer overflow may occur.
When scanf is used, if the read width is specified, no error is reported. Modify the Code as follows:
#include "stdio.h"int main(void){ int i; printf("Input i\n"); scanf_s("%5d", &i); printf("i is %d", i); return 0;}
The read width of % d is 5. However, when the read data exceeds the Width limit, the data will be lost. For example, this is input 100000, and the output I value is 10000.
Solution
1. Specify the width when scanf is used.
2. Replace sacnf with sacnf_s.
3. Cancel the SDL check when creating a new project.