Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for the Output

Tags:

c

#include<stdio.h>
int main(void)
{
 int a=5;
 printf("%d"+1,a);
}

Output: d. I didn't get how the output is coming: d ?

like image 521
Parikshita Avatar asked Nov 26 '22 23:11

Parikshita


1 Answers

You passed as first argument of printf "%d"+1; "%d" is actually seen as a const char * that points to a memory location where %d is stored. As with any pointer, if you increment it by one, the result will point to the following element, which, in this case, will be d.

a is not used, but this should not be a problem since in general (I don't know if it's standard-mandated Edit: yes it is, see bottom) the stack cleanup responsibility for variadic functions is up to the caller (at least, cdecl does it that way, this however may or may not be UB, I don't know*).

You can see it easier this way:

#include<stdio.h>
int main(void)
{
    int a=5;
    const char * str="%d";
    printf(str + 1, a);
}

 

str ---------+
             |
             V
          +----+----+----+
          |  % |  d | \0 |
          +----+----+----+

str + 1 ----------+
                  |
                  V
          +----+----+----+
          |  % |  d | \0 |
          +----+----+----+

Thus, ("%d"+1) (which is "d") is interpreted as the format string, and printf, not finding any %, will simply print it as it is. If you wanted instead to print the value of a plus 1, you should have done

printf("%d", a+1);


Edit: * ok, it's not UB, at least for the C99 standard (§7.19.6.1.2) it's ok to have unused parameters in fprintf:
If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.

and printf is defined to have the same behavior at §7.19.6.3.2

The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.
like image 82
Matteo Italia Avatar answered Jan 01 '23 19:01

Matteo Italia