Difference between scanf and scanf_s

老子叫甜甜 提交于 2019-11-26 16:35:48
ironslab

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.

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.

BTW, the reason your compiler is giving you an error, and stopping, rather than the 'warning' the issue actually is, is that you must have your Visual Studio setup such that it will "treat all warnings as errors". Change the configuration to let warnings be warnings, and you can then also just ignore this warning.

What you can do to avoid this error is to paste the thing between the <>: <_CRT_SECURE_NO_WARNINGS> to a place. To get to the place right click on your project in the solution explorer and click on the properties. then go to the configuration properties, then the c/c++, then the preprocessor. then in preprocessor definitions, after everything, add a semicolon and paste the thing in. then press apply and ok. Your problem should be solved.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!