3

When providing the wrong number of arguments to printf():

printf("%s", "foo", "bar");

or when by providing arguments of the wrong type:

printf("%d", "foo");

gcc is able to warn about these mistakes:

$ gcc -Wformat printf_too_many_arguments.c
printf_warnings.c: In function `main':
printf_warnings.c:5: warning: too many arguments for format
printf_warnings.c:5: warning: too many arguments for format

$ gcc -Wformat printf_argument_of_wrong_type.c
printf_warnings.c: In function `main':
printf_warnings.c:5: warning: format `%d' expects type `int', but argument 2 has type `char *'
printf_warnings.c:5: warning: format `%d' expects type `int', but argument 2 has type `char *'

How to get such warnings with Visual Studio 2005?

-- dave

user418190
  • 31
  • 2
  • The gcc compiler has special code in it that "knows" about the printf function and the format string. as far as I'm aware the MS compiler does not have this. –  Aug 12 '10 at 09:13

3 Answers3

1

I use cppcheck (http://cppcheck.sourceforge.net/) when working with Visual Studio 2005 which detects mismatches between the number of parameters provided to printf/wprintf and the number of parameters required.

Unfortunately it doesn't check the types match, but it's a start.

Andy Krouwel
  • 1,309
  • 11
  • 21
0

Unfortunately MSVC/Visual Studio does not support this.

See also __attribute__((format(printf, 1, 2))) for MSVC?

Community
  • 1
  • 1
nos
  • 223,662
  • 58
  • 417
  • 506
  • 1
    Thanks for the info. The lack of such warnings from Visual Studio is really bad. – user418190 Aug 12 '10 at 10:06
  • Visual Studio has supported this for almost 10 years (including in VS2005): http://msdn.microsoft.com/en-us/library/ms235402(v=vs.80).aspx, just pass the /analyze flag. – Mooing Duck Aug 28 '14 at 01:28
0

You will need additional software to do this. Take a look at PC-Lint (http://www.gimpel.com/). It can find these kinds of errors (and much more [potential] errors as well).

Patrick
  • 23,217
  • 12
  • 67
  • 130