C language (i) scanf (), scanf_s () and error C4996

Source: Internet
Author: User

Fatal error C4996

Beginner C, the first I/O function to touch is scanf (). However, when compiling code in a later version of Visual Studio (including but not limited to 2015, 2013, 2012), unexpected errors occur.
Here's a simple code:

 #include  " stdio.h  "  int  Main (void   int   I; printf (  " input i\n  "  ); scanf (  " %d      ", &i); printf (  " i is%d  "  , I);  return  0  ;}  

But it will output an error C4996, the error message is as follows

Error 1 C4996: ' scanf ': This function or variable could be unsafe. Consider using scanf_s instead. To disable deprecation, use _crt_secure_no_warnings. See online Help for details.

Error said scanf unsafe, recommended to replace scanf scanf_s. After the 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  ;}  

There are no error hints.

scanf and scanf_s

In MSDN there are functions that end with _s, including scanf_s, scanf_s_l, wscanf_s, and _wscanf_s_l. These versions of the functions have security enhancements.

scanf functions exist in the older CRT (C Runtime Library, part of the C library) and have security issues, such as when reading a character, without specifying the width of%s, can cause a buffer overflow.

When using scanf, if the read width is specified, no error will be made. 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  ;}  

This controls the read-in%d width of 5. However, when the data read exceeds the width limit, data is lost. For example, this is input 100000, the output I value is 10000.

Workaround

1. Specify the width when using scanf.

2. Replace the sacnf with sacnf_s.

3. Cancel the SDL check at the time of the new project.

C language (i) scanf (), scanf_s () and error C4996

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.