Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between scanf and scanf_s

What is the difference between scanf and scanf_s? In the university I have been taught and I am using scanf, but at my personal computer Visual Studio keeps sending this warning.

 error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead.

And I have to change all scanf to scanf_s or the program won't build. (I am using Visual Studio 2013)

like image 600
Tony Andreev Avatar asked Jan 29 '14 14:01

Tony Andreev


People also ask

What is difference between scanf and scanf_s?

scanf originally just reads whatever console input you type and assign it to a type of variable. scanf_s has an parameter, When you read a string, the parameter must be provided to indicate how many characters are read at most to prevent overflow.

Should I use scanf_s?

In the posted code there is no reason to use scanf nor scanf_s in the swap function. scanf_s is a function introduced by Microsoft as a supposedly safer(1) alternative to scanf that is too often used carelessly by unsuspecting programmers, especially for %s , %[ and %c conversions, leading to security flaws.

How does scanf_ s work?

The scanf_s function reads data from the standard input stream, stdin , and writes it into argument . Each argument must be a pointer to a variable type that corresponds to the type specifier in format . If copying occurs between strings that overlap, the behavior is undefined.


2 Answers

It is a function that belongs specifically to the Microsoft compiler.

scanf originally just reads whatever console input you type and assign it to a type of variable.

If you have an array called first_name[5] and you use scanf for "Alex", there is no problem. If you have the same array and assign "Alexander", you can see it exceeds the 5 slots that the array contains, so C will still write it on memory that doesn't belong to the array and it might or might not crash the program, depending if something tries to access and write on that memory slot that doesn't belongs to first_name. This is where scanf_s comes in.

scanf_s has an argument(parameter) where you can specify the buffer size and actually control the limit of the input so you don't crash the whole building.

like image 179
0xFED5550 Avatar answered Oct 01 '22 15:10

0xFED5550


scanf_s() is not described by the C99 Standard (or previous ones).

If you want to use a compiler that targets C99 (or previous) use scanf().

For C11 Standard (and eventually later ones) scanf_s() is much harder to use than scanf() for improved security against buffer overflows.

C11 fscanf_s(): http://port70.net/~nsz/c/c11/n1570.html#K.3.5.3.2

~~~~~~~~~~~~~~~~

If you have a C99 compiler with extras that provides scanf_s() as an extension and don't mind losing portability, check your compiler documentation.

like image 41
pmg Avatar answered Oct 01 '22 14:10

pmg