is scanf_s portable?

I have a question about the use of scanf_s vs. scanf. I'm writing C code using microsoft visual C++ and when I try to use scanf (or fscanf etc...) I get a warning which suggests using scanf_s, but I have never seen scanf_s in any of my books or in the c language refs I have seen online. So my question is, is scanf_s portable, ie is it part of the ANSI standard? Will other compilers recognize it? Also, any opinion as to which is better to use, scanf_s vs scanf? Thanks for any info you can give.
No, scanf_s() is Microsoft-specific.

Any format string of the form "%s" is dangerous because it doesn't prevent buffer overflow (a security concern). For all such functions MS introduced 'secure' versions, like scanf_s().

But plain-old scanf() is the ANSI standard, and it is not deprecated by anyone but MS.

Just make sure there is always a number between % and s in your format strings.


There are several ways you can fix things.

1. #define _CRT_SECURE_NO_DEPRECATE before you include any headers and just use the ANSI scanf().

2. Use a little preprocessor magic for non-VC++ compilers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ifndef _MSC_VER

  #define scanf_s( fmt, ... ) scanf( scanf_validate( fmt, __FILE__, __LINE__ ), __VA_ARGS__ )

  const char* scanf_validate( const char* fmt, const char* file, long line )
    {
    const char* p = fmt;
    while (1)
      {
      p = strstr( p, "%s" );
      if (p == NULL) break;
      if ((p == fmt) || (*(p-1) != '%'))
        {
        fprintf( stderr, "Hey, you used \"%%s\" in %s: line %d!\n", file, line );
        abort();
        }
      }
    return fmt;
    }

#endif 


Hope this helps.
Duoas,

Thanks for the reply, just the info I was looking for.

Your option 1 is what I had been doing previously, but maybe I'll switch over to option 2 for extra security.

Thanks again.
Topic archived. No new replies allowed.