sacnf_s () function Small note

Source: Internet
Author: User

I've been wondering why the scanf () function of the C program always gets an error on visual Stdio2013, but it is correct to copy the program to other compilers. So when using the VS programming program, always mechanically follow the scanf_s () to replace the scanf () function as it reminds me, although I don't know why, but there is no problem. Know today, when I want to read into a string, as follows:

#include <stdio.h><string.h>int main (void) {     char str [+];     scanf_s ("%s", str);     printf ("%d%s", strlen (str), str);      return 0 ;}

Result output: 0

My first reaction is that the scanf_s () function and scanf () do not seem to be exactly equal (this is not nonsense, at least before the problem, I have been directly using the scanf () grammar directly on the scanf_s (), so I searched for a bit, the result is as follows: this function is specific to Microsoft compilers.  It is the same as scanf, except it does not cause buffer overload. It takes the input in a, text based console program, and places it into a variable. –from here

Originally it is Microsoft's compiler dedicated, such as Vc++,vs (vs after 2013), because the scanf () function input does not check the subscript, if the input string length is greater than the length of the declaration, may be written to other memory, resulting in an unknown error, and scanf_s () The function is improved based on scanf (), and the input string is incremented with a length parameter, as the code above can be changed to:scanf_s ("%s", str, 100), This allows the program to read only the first 99 characters and then add a ' 0 ' if the input is overrun.

Say to yourself: out of the mix, always have to, avoid better take away

sacnf_s () function Small note

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.