Why is scanf
() considered unsafe in Visual Studio?
When in Visual Studio,I must use scanf_s
instead of scanf
.
Asked
Active
Viewed 2,086 times
1

Saeed All Gharaee
- 1,546
- 1
- 14
- 27

Volta-Hsu
- 19
- 3
-
2You don't *need* to use `scanf_s`, and the warning tells you how to disable it. Add `#define _CRT_SECURE_NO_WARNINGS` before including any standard library files. The reason `scanf` is unsafe is that you can use `%s` as a format string and have a buffer overflow because there's no limit on what it will read. You should always use a width specifier like `%99s`. – Retired Ninja Dec 21 '21 at 02:44
-
Good description of some issues: [Difference between scanf's width specification and scanf_s](https://stackoverflow.com/questions/40421378/difference-between-scanfs-width-specification-and-scanf-s) – Retired Ninja Dec 21 '21 at 02:46
-
1[All of the `_s` functions are unportable, don't solve the problems Microsoft intended them to solve, and should not be used](https://stackoverflow.com/questions/60326623/im-using-linux-compiling-with-gcc-getting-error-warning-implicit-declaratio/60326678#60326678). However, [all of the `scanf` functions are broken as specified, and should not be used either](https://stackoverflow.com/questions/58403537/what-can-i-use-for-input-conversion-instead-of-scanf). – zwol Dec 21 '21 at 02:49
-
Here's a [nice analysis](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm) of the actual, practical safety and usage considerations of the `_s` functions – Steve Summit Dec 21 '21 at 03:07
-
`scanf()` is unsafe because it will, for some format specifiers (like `%s`) and depending on user input, happily overwrite buffers. Techniques to mitigate that exist but don't work if the programmer doesn't use them. `scanf_s()` provides a *partial* solution to such problems by requiring use of width specifiers in such cases - but don't work if programmers provide wrong widths (i.e. `scanf_s()` address one set of problems by introducing a new set). Microsoft originally designed `scanf_s()` so all Microsoft compilers since diagnose usage of `scanf()` and push usage of `scanf_s()` by default – Peter Dec 21 '21 at 03:13
-
Microsoft also insists that `strcpy` is unsafe, which is sort of agreeable. It says `fopen` is unsafe, that one is pushing it. Whatever problems these functions have can be managed by screening the input. The `_s` functions don't automatically solve any problems. Disabling the warning is a reasonable option. – Barmak Shemirani Dec 21 '21 at 04:28
-
Visual Studio is considered unsafe. Consider using Visual Studio_s instead. – Lundin Dec 21 '21 at 07:19
-
They want vendor lockin so your code doesn't work with other compilers. – Shawn Dec 21 '21 at 07:36