When I use visual studio, it says "scanf is unsafe, try using scanf_s". But if I use scanf_s in gcc or other compilers, it doesn't work. Does scanf_s works only on visual studio? If so, why? The visual studio website says "scanf is unsafe". If it is unsafe, then why others still uses it?
1 Answers
scanf_s
is Microsoft-specific. Header is stdio.h but not in GCC.
When reading a string with
scanf
, always specify a width for the%s
format (for example, "%32s
" instead of "%s
"); otherwise, improperly formatted input can easily cause a buffer overrun.
Alternately, consider usingscanf_s
,_scanf_s_l
,wscanf_s
,_wscanf_s_l
orfgets
.
See more at "Why didn't gcc implement _s
functions?"
pmg
adds in the comments that scanf_s()
is Standard C11 (optional).
That means that activating c11
with gcc
might be enough.
However Shawn adds:
IIRC, Microsoft's version doesn't follow the standard.
Plus no other major C library vendor has bothered to implement Annex K, so it might as well be MS specific for all intents and purposes.
pmg
confirms:
My
gcc
(version 6.3.0) does not recognizescanf_s()
withgcc -std=c11 -pedantic ...

- 1,262,500
- 529
- 4,410
- 5,250
-
`scanf_s()` is Standard [C11 (optional)](http://port70.net/~nsz/c/c11/n1570.html#K.3.5.3.2) – pmg Jun 01 '19 at 07:26
-
1@pmg IIRC, Microsoft's version doesn't follow the standard. Plus no other major C library vendor has bothered to implement Annex K, so it might as well be MS specific for all intents and purposes. – Shawn Jun 01 '19 at 07:29
-
@pmg So activating c11 with gcc would be enough? (https://stackoverflow.com/questions/16256586/how-to-enable-c11-on-later-versions-of-gcc) – VonC Jun 01 '19 at 07:29
-
My gcc (version 6.3.0) does not recognize `scanf_s()` with `gcc -std=c11 -pedantic ...` – pmg Jun 01 '19 at 07:35