Hi guys,
This is my first post here at Cplusplus forums.So if this question is in the wrong section please move it there.
So, I was stuck in a question when my teacher gave me the following code
1 2
x = 2;
printf("%d %d",x);
Upon running the code on both gcc and the outdated Turbo C compiler, I found two very different outputs.
The gcc compiler gave the expected output of 2 and junk value.
But the turbo c compiler gave the output 2 2 .
Any reason why this could be the answer?
PS : This is not my homework.The teacher casually just gave me this question to find the output.
Thanx !
I believe, and someone is going to have to correct me if I'm wrong. That this is undefined behaviour. the gcc compiler gave you the correct output, because it's suppose to be printf("%d %d", x, x); while the very outdated turbo C was undefined behaviour, in which case anything can happen.
As for what does it mean that the behavior is undefined, see http://en.cppreference.com/w/cpp/language/ub -- in short, anything at all may happen, including any output, crash, whatever. The program is invalid and there is no reasoning about its behavior.
The behavior is, as the others have pointed out, undefined. But by looking at the produced assembly it is possible to determine what the program will do (even though the compiler is not guaranteed to output the same assembly twice).
The variable x is on the stack, since it's a local variable. The arguments of a function call are (in 32-bit mode cdecl calling convention) on the stack too. The turbo C compiler might have put the local variable directly next to the function arguments. Giving this stack:
---------------
| other data |
---------------
| x |
---------------
| printf arg 1 |
---------------
| printf string |
---------------
As function arguments are pushed left to right, the variable x will end up at the exact location printf expects to find its second argument, causing it to print this instead. Adding another variable between x and the printf call will most likely make it print this value instead.
On gcc, the stack must be aligned to 16-byte boundary. So gcc will most likely have some padding bytes between the local variable and the function arguments if the variables are not 16-byte aligned. This will cause printf to read from the padding bytes, printing whatever was there (garbage).
But all of this behavior is strictly undefined, so you should not rely on it. But using assembly it is possible to explain all these details.