Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf(): When is %n written?

Consider the following code:

#include <stdio.h>

int main() {
  int i = 0;
  printf("hello%n%d\n", &i, i);
}

Why does it print hello0 and not hello5?

like image 544
delta242 Avatar asked Mar 08 '23 15:03

delta242


1 Answers

When you call a function, the function arguments are copied into the scope of the called function. Since i is 0, the value 0 is copied into the scope of printf and used to print in the %d conversion.

Additionally, the value &i is copied into the scope of the function, and the function uses that value to populate the variable at that address with the number of output bytes so far. So after your function call returns, you can inspect i to find that value.

The fact that you used the same variable to both produce a value for the %d argument and to produce an address for the %n argument is pure coincidence. In fact, the last i argument is really a bit misleading, since it is not the identity of i that matters here, but only its value. You might as well have put a literal 0 there. (Technically, the expression i undergoes "lvalue conversion", which is just a fancy way of saying that you don't care about the variable, only the value.)

like image 156
Kerrek SB Avatar answered Mar 19 '23 15:03

Kerrek SB