Printf without explanation

I understand that if printf has no arguments, it prints an unexpected value.

Example:

#include <stdio.h> int main() { int test = 4 * 4 printf("The answer is: %d\n"); return 0; } 

This returns a random number. After playing in different formats, such as% p,% x, etc., It does not print 16 (because I did not add the variable to the argument section). I would like to know where these values ​​come from? Is this the top of the stack? This is not a new value every time I compile, which is strange, it is like a fixed value.

+5
source share
4 answers
 printf("The answer is: %d\n"); 

causes undefined behavior. C requires a conversion specifier to have an associated argument. Although this behavior is undefined and something can happen, on most systems you end up dropping the stack. This is a trick used in formatting string attacks .

+5
source

It is called undefined behavior , and it is scary (see this answer ).

If you need an explanation, you need to dive into the specific implementation details. Therefore, examine the generated source code (for example, compile your optimization flags with gcc -Wall -Wextra -fverbose-asm +, then look at the generated .s assembly file) and your system ABI .

+4
source

The printf function will look for an argument on the stack, even if you do not add it. All that will be used there if it cannot find an integer argument. In most cases, you will get meaningless data. The selected data varies depending on your compiler settings. On some compilers, you can get 16 as a result.

For instance:

 int printf(char*, int d){...} 

This is how printf will work (not really, just an example). It does not return an error if d is empty or empty, it just looks at the stack for the argument that should be displayed there.

+2
source

Printf is a variable function of the argument. Most compilers push the arguments onto the stack and then call the function, but depending on the machine, operating system, calling conventions, number of arguments, etc., there are other values ​​that are pushed onto the stack that may be constant in your function .

Printf reads this memory area and returns it.

+1
source

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


All Articles