user9679818
user9679818

Reputation: 103

Why does a function print the value of a local auto variable from a function called earlier?

#include<stdio.h>

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

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

int main()
{
    foo();
    boo();
}

Why does boo print the value of a from foo? I read an explanation about the execution stack and activation frames but I do not understand it.

Upvotes: 1

Views: 83

Answers (1)

Joy Allen
Joy Allen

Reputation: 402

This is how your function is called(a).

                   stack
---------------------------------      call             return
---------------------------------
               |                |
earlier frame  | earlier frame  |
               |                |
---------------------------------
---------------------------------
               |                |                     (5) pop old %ebp to %ebp
               |----------------|
caller's frame | func arguments | (1) push args
               |----------------|
               | return address | (2) push ret-addr   (6) reset %esp here
---------------------------------
---------------------------------
               | old %ebp       | (3) push old %ebp   (4) reset %esp = %ebp
               |----------------|     reset %ebp here
               |                |
callee's frame | local variables|
               |                |
---------------------------------
---------------------------------

When a function returns, the data in its frame may be kept. So, in your case, boo() used the same frame with old data of foo().


(a) Nothing in the standard guarantees this, it's just the most likely explanation for your particular scenario.

Upvotes: 3

Related Questions