oob
oob

Reputation: 1958

What are possible consequences of format/argument type mismatches in c++ fprintf function calls?

We have a legacy c++ .dll compiled for windows under visual studio. We have been running into issues where we get different results when we compile the program using different compiler options.

I have done a pretty simple port so that I can compile it under linux using g++. I just wanted to see what kind of warnings gcc would throw at me and possibly try to run it using valgrind to look for possible erros.

So that is the background. Here is the question. We have a bunch of fprintf function calls that print to a log file. When compiled under g++, I get warnings like this.

../f11.cpp:754:128: warning: format ‘%i’ expects type ‘int’, but argument 8 has type ‘long unsigned int’

Obviously this is a bad thing we need to fix, but I am just curious about the potential consequences of ignoring this warning? Are the consequences only limited to the output in the log file, or could this cause things like buffer overruns or any other type of situation where we are overwriting memory without knowing it?

Upvotes: 0

Views: 177

Answers (2)

You are getting such warnings because of code like

 long x;
 printf ("x=%i\n", x);

On a 64 bits x86-64 Linux machine, what is probably happenning is that printf implementation would call va_arg(arglist, int) for the x argument. Since int is 32 bits and long is 64 bits, the 64 bits value is probably truncated to its 32 lower bits, which in that particular case probably don't harm much.

If it is a scanf ("%i", &x); things become much much uglier. Probably, only 32 bits out of 64 of the long x get changed, and that will break the code later.

But as everyone responded, this is undefined behavior. you'll feel sorry if you don't fix it or at the very least, add a big fat /* FIXME */ comment for the person working on the code in a few weeks or months.

Upvotes: 1

Mysticial
Mysticial

Reputation: 471299

By definition, it's undefined behavior to have mismatching format strings and argument types.

So anything is allowed to happen. But more likely, you'll get completely garbled and non-sense output - especially if the sizes of the operands you pass don't match what's expected from the format strings.

It is possible for a buffer overrun to happen - if printf() ends up reading past the parameters, it will be reading stack garbage. But it will only reading it. It won't be writing to it, so it shouldn't corrupt anything. (with one exception - %n, see comments)

But then again, it's undefined behavior. Anything is possible.

Upvotes: 6

Related Questions