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 warn开发者_C百科ings with Visual Studio 2005?
-- dave
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.
Unfortunately MSVC/Visual Studio does not support this.
See also __attribute__((format(printf, 1, 2))) for MSVC?
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).
精彩评论