Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 327
Christian Ammer Avatar asked Jan 24 '13 14:01

Christian Ammer


People also ask

What happens if you use the wrong format specifier in C?

Incorrectly specified format strings can result in memory corruption or abnormal program termination.

What format is used to print a string with the printf function?

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.

What causes format string vulnerability?

The Format String exploit occurs when the submitted data of an input string is evaluated as a command by the application.

Is string format the same as printf?

String. format returns a new String, while System. out. printf just displays the newly formatted String to System.


1 Answers

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.

like image 88
Alok Save Avatar answered Nov 01 '22 23:11

Alok Save