What can happen if printf is called with the wrong format string?

Or in other words: Can an incorrect printf / fprintf string of a decimal integer ( %d , %u , %ld , %lld ) lead to a program crash or undefined behavior?

Cosine 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; } 

The result for 32-bit architecture:

 4 4 10, 20 

Result in architecture with 64-bit architecture:

 4 8 10, 20 

In any case, the program prints the expected result. I know if the long value exceeds the range of int , the program prints the wrong numbers - which is ugly, but does not affect the main purpose of the program - but can anything unexpected happen besides this?

+4
source share
5 answers

What can happen if printf is called with the wrong format string?

Everything can happen. This is undefined behavior!
Undefined behavior means that anything can happen. It may show you the results that you expect, or it may be wrong, or it may fail. Anything can happen, and you can blame anyone but yourself for this.

Link:

c99 Standard: 7.19.6.1:
point 9:

If the conversion specification is not valid, the behavior is undefined. 225) If any argument is not the correct type for the corresponding coversion specification, the behavior is undefined.

+6
source

Oh yes - printf depends on the format string to determine the size and type of the variable for subsequent selection. If the format string is incorrect, it may try to get a variable that does not even exist, with all the ensuing consequences.

+1
source

This behavior is undefined - there is nothing in the specification telling the compiler developer (or the C library constructor) how to handle this, and therefore they are allowed to do something.

In practice, this is one of those where it is fully consistent with the interpretation of numbers, and most likely you will never get anything good from it. It’s very bad when you mix the string with the whole formatting - the strings will print beautifully like (strange, maybe) numbers, but the numbers hardly "work" when transmitted as strings - because the string is a pointer to the address of the first character - and most numbers are not valid pointers in a typical system, so it will crash.

But there is no guarantee. In your 64-bit example, it is clear that the number is "a little endian". Try the same with 0x100000000 and it will print 0 - because the rest of the number will be lost.

+1
source

This can happen if printf is called with the wrong format string. Its behavior is undefined and you should never rely on undefined behavior.

+1
source

Do not use printf

printf is a relic of C days and is no longer needed ... Instead, use std::cout and I / O manipulators.

0
source

Source: https://habr.com/ru/post/945270/


All Articles