Tom
Tom

Reputation: 19302

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 determine an argument is missing at runtime?

Upvotes: 3

Views: 464

Answers (3)

Roland Illig
Roland Illig

Reputation: 41686

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))).

Upvotes: 5

orlp
orlp

Reputation: 117846

Nope there isn't, C will allow you to shoot yourself in the foot just like that.

Upvotes: 0

Mark Wilkins
Mark Wilkins

Reputation: 41252

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.

Upvotes: 2

Related Questions