Or in other words: Could a wrong printf
/ fprintf
decimal integer (%d
, %u
, %ld
, %lld
) format string cause a program to crash or lead to undefined behavior?
Cosinder following lines of code:
#include <iostream>
#include <cstdio>
int main() {
std::cout << sizeof(int) << std::endl
<< sizeof(long) << std::endl;
long a = 10;
long b = 20;
std::printf("%d, %d\n", a, b);
return 0;
}
Result on 32 bit architecture:
4
4
10, 20
Result on 64 bit architecture:
4
8
10, 20
In any case the program prints the expected result. I know, if the long
value exceeds the int
range, the program prints wrong numbers – which is ugly, but doesn't effect the main purpose of the program –, but beside this, could anything unexpected happen?
Incorrectly specified format strings can result in memory corruption or abnormal program termination.
The printf prototype is defined in the <cstdio> header file. When you use the printf() function, it prints the string pointed out by the format to the standard output stdout. The format can also contain some specifiers that start with a % and replace values of variables with the printf() function.
The Format String exploit occurs when the submitted data of an input string is evaluated as a command by the application.
String. format returns a new String, while System. out. printf just displays the newly formatted String to System.
What can happen if printf is called with a wrong format string?
Anything can happen. It is Undefined behavior!
Undefined behavior means that anything can happen. It may show you results which you expect or it may not or it may crash. Anything can happen and you can blame no one but yourself about it.
Reference:
c99 Standard: 7.19.6.1:
para 9:
If a conversion specification is invalid, the behavior is undefined.225) If any argument is not the correct type for the corresponding coversion specification, the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With