Reputation: 243
I wrote a small code of C.
#include<stdio.h>
int main()
{
int a = 0;
printf("Hello World %llu is here %d\n",a, 1);
return 0;
}
It is printing the following ouput
Hello World 4294967296 is here -1216225312
With the following warning on compilation
prog.cpp: In function ‘int main()’:
prog.cpp:5: warning: format ‘%llu’ expects type ‘long long unsigned int’, but argument 2 has type ‘int’
I know i need to cast the int to long long unsigned int, but i could not understand the fact that why the later values got corrupted.
Thanks in advance
Upvotes: 3
Views: 3573
Reputation: 755034
The format you passed to printf()
leads it to expect 12 bytes on the stack, but you only push 8 bytes. So, it reads 4 bytes you didn't push, and gives you unexpected output.
Make sure you pass what printf()
expects, and heed your compiler's warnings.
Upvotes: 3
Reputation: 43331
According to given format, printf reads memory region 64 bit length, which contains a and 1 together, an prints 4294967296. Then it reads some junk from the next 32 bits and prints -1216225312.
Upvotes: 0
Reputation: 64283
Long long is 64 bits long, therefore what happens is this :
1. printf grabs 64-bits and print it as the 1st argument
2. then it grabs 32 bit at the offset of 64 bits, and print it
Since you are passing 32 bits value to the 1st argument, both values are garbage
Upvotes: 0
Reputation: 471569
%llu expects a 64-bit integer. But you only gave it a 32-bit integer.
The effect is that what printf is reading is "shifted" over by 32-bits with respect to what you've passed. Hence your "1" is not being read in the right location.
EDIT:
Now to explain the output:
a
and 1
are being stored 32-bits apart because they are both 32-bit integers.
However, printf expects the first argument to be a 64-bit integer. Hence it reads it as a + 2^32 * 1
which is 4294967296
in your case. The second value that is printed is undefined because it is past the 1
.
Upvotes: 7
Reputation: 206636
Because the code causes an Undefined Behavior.
An Undefined Behavior inherently means tha all bets are off.
printf
is not type safe. You have to be careful in telling printf
the proper format desrciptor while printing out types.
Upvotes: 4