Difference between scanf and scanf_s

Tony Andreev picture Tony Andreev · Jan 29, 2014 · Viewed 83.2k times · Source

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)

Answer

0xFED5550 picture 0xFED5550 · Jan 29, 2014

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.