When I try to explain some simple code to my friends,something strange happens:
#include <stdio.h>
int main()
{
int x;
printf("%x\n",x);
}
I have tryed millions of times ,and the last 12 bits of x always turns out to be 0xff0.
I’ve disass the code,but still can’t figure out what’s going on here
My operating system is ubuntu10.10 ,compiler is gcc4.7.2
First of all, if the value always matches 0xFF0 then the “lower 12 bits” are that value, not the lower 3.
As for why this happens, you’re reading a variable that you haven’t initialized. That’s undefined behavior, and anything could have happened when you tried to do this, from a crash to a pizza getting delivered.
But what actually happens is this: the location that x references has some data that it held previously. Chances are that on your setup, that variable happens to contain data whose lower twelve bits are 0xFF0; in which case it’s most likely data associated a previous system call, during processing work done by the system before your
mainis called.To make a long story short: initialize your variables before using them and don’t ask why the uninitialized ones have the value they do.