Exploring My Technical Learnings... Which could be a doubt or solution..!
Tuesday, October 12, 2010
C Program where, registers playing a role, unknowingly....!
Few days back, when I was assisting one of my colleagues in learning C language, one C program didn’t work as I expected. The program was to explain the stack concept in storing local variables.
main()
{
int a=10;
int b=20;
int *ptr;
ptr = &a;
ptr--;
printf("%d %d\n",*ptr);
}
Conceptually, a, b and ptr will be stored in stack because of its local scope. Hence address will decrement from a to b. As a result, *ptr should give the value of b. But at that point of time, it was not like that...! I was surprised...! I have tested in my machine as follows.
main()
{
int a=10;
int b=20;
int *ptr;
ptr = &a;
ptr--;
printf("%u %u %u\n", &a, &b, ptr);
printf("%d %d\n",*ptr);
}
When I tested this program, the output was as I expected. Say, 1000, 996, 996 and 20. Once again I surprised...! In my machine, the output is different and in my colleague's system, the output if different for the same program and same GCC compiler....!!!!!! Once again looked into both programs, there was no difference except address printing line. Thought that address printing line won’t affect the output.
But after some days, I have discussed this thing and I came to know that, if registers are available and if there is no explicit reference to the variables, then compiler could use CPU registers to store the local variables. Because of that only, stack operation result was reflecting in the output. When I try to print the address explicitly, then compiler should use the memory location to store the local variables. Hence stack operation was successful.
It doesn’t mean that, every compiler behaves like this. I found this behavior in GCC. There could be some other compilers which can use stack memory for storing local variables even though we don’t try to fetch the address of the variables. All depends on Compilers....
Gud luk...
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment