How can I ensure vfprintf has the proper number of arguments?
I have a variable-argument function in C that looks roughly like this:
void log(const char * format, ...) {
va_list args;
va_start(args, format);
vfprintf( stderr, format, args );
va_end(args);
exit(1);
}
I was able crash my app by callilng it like this,
log("%s %d", 1);
because the function was missing an argument. Is there a way to determi开发者_开发百科ne an argument is missing at runtime?
No, there isn't. But when you compile your code with gcc, you should add the options -Wall -Wextra -Wformat -Os
. This will enable lots of warnings, and when you annotate your function with __attribute__(__printf__, 2, 3)
or something similar (I don't remember the exact syntax), a warning for exactly your case should appear.
See http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html for the exact syntax. It's really __atttribute__((__format__(__printf__, 1, 2)))
.
I don't believe there would be any standard mechanism for determining that at runtime. The parameters after the format specifier are simply values on the stack. For example, if a format specifier indicated a 4-byte integer was next, there would be no way of knowing if the next 4 bytes on the stack were an integer or just whatever happened to be on the stack from a previous call.
Nope there isn't, C will allow you to shoot yourself in the foot just like that.
精彩评论