Why is the value of the automatic object stored after the end of its life?

I'm getting ready for an interview.

My program c:

void foo(void)
{
    int a;
    printf("%d\n",a);
}

void bar(void)
{
    int a=42;
}

void main(void)
{
    bar();
    foo();
}

I get output like: 42

But how? I thought it would be some kind of trash value.

How is the concept of an execution stack or activation frame applied?

Please explain

thanks

+4
source share
3 answers

anot initialized by function foo. Printing an uninitialized variable causes undefined behavior .
In this case, you can get anything, the expected or unexpected result. In my compiler, output

 4203214  

, .
, 42, , . bar, 42 . . foo, a 42.
( -o), a.

+5

bar() 42 . , foo().

bar() foo(), , , , , a in foo() 42.

, Undefined . , , , .

( , gcc), , , .

+3

bar() main(), a = 42, int , main(). foo() main(), a, , int , main().

bar(), , foo() bar() , bar() a foo() a .

, undefined. .

+1

Source: https://habr.com/ru/post/1524082/


All Articles