Home >Backend Development >C++ >Why Can Wrong Format Strings in printf/fprintf Lead to Undefined Behavior?
When using printf or fprintf for decimal integer formatting (%d, %u, %ld, %lld), it's crucial to ensure that the specified format matches the data type being formatted. Otherwise, undefined behavior can occur.
Defining undefined behavior in programming is challenging, as it encompasses a vast range of possible consequences, including:
Consider the following code snippet:
#include <stdio.h> int main() { long a = 10; long b = 20; printf("%d, %d\n", a, b); }
On a 32-bit architecture, the result is as expected: "10, 20". However, on a 64-bit architecture, the output changes to "10, 2097152".
This anomaly is because printf interprets the '%d' format specifier as an int type placeholder, which is 32 bits on a 32-bit architecture. But on a 64-bit architecture, int is 64 bits, resulting in incorrect conversion for long values.
Using incorrect format strings can have severe consequences:
The above is the detailed content of Why Can Wrong Format Strings in printf/fprintf Lead to Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!