I'm preparing for a job interview.
My c program is :
void foo(void)
{
int a;
printf("%d\n",a);
}
void bar(void)
{
int a=42;
}
void main(void)
{
bar();
foo();
}
I'm getting the output as : 42
But how? I thought it would be some garbage value .
How the concept of execution stack or activation frame is applied in this?
Please explain
Thanks
a
is not initialized in function foo
. Printing an uninitialized variable invokes undefined behavior.
In this case you may get anything, either expected or unexpected result. On my compiler the output is
4203214
The result may vary compiler to compiler, even different versions of same compiler could give you different results.
But one of the possible reason that you are getting 42
is because auto variables are often allocated on an execution stack. After the call of bar
, 42
is placed on execution stack. This value remains in stack undisturbed. When foo
is called, it might read that stack space for a
and prints 42
.
Try to optimize your code (compile with -o
), you may get some different value for a
.
The call to bar()
puts the value 42
on the stack. It is still there when foo()
is called.
The stack frames of bar()
and foo()
are likely identical, or a least similar enough, so that the a
in foo()
keeps the value 42
.
Of course, this is not guaranteed, and is Undefined Behavior. But rather than simply dismissing such questions, as is often done, for debugging code one often needs some understanding.
If you increase the optimizing level (at least in gcc), the behaviour you see would change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With