Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does value of automatic object persist after lifetime ends? [closed]

Tags:

c

output

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

like image 895
HighBoots Avatar asked Jan 12 '23 08:01

HighBoots


2 Answers

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.

like image 94
haccks Avatar answered Jan 17 '23 15:01

haccks


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.

like image 23
Joseph Quinsey Avatar answered Jan 17 '23 15:01

Joseph Quinsey