Yes, the value 42 is a garbage. Here is the explanation for it:
Every function in stack, starts similar to this order
- Parameters of the function
- Return value of the function
- EBP( Which stores previous frame pointer)
- Exception handler frame
- Local variables
- Buffer
- callee save register
In the above example, main()
is called and follows the procedure as above.
Then it encounters the bar()
follows 1,2,3,4 steps mentioned and then stores the local variable a=42
in the memory(5) then 6,7 are followed then it will come out of the memory.
Then it encounters the foo()
follows 1,2,3,4 steps as same in the memory location that bar()
had. And you declared a local variable called a
which will point to same memory location that bar()
holding the local variable a=42
. So it is giving the same value 42 when you are printing, which is actually a garbage value.
To validate this, try this example: This prints 7
#include <stdio.h>
#include <string.h>
void foo() {
int b;
printf("%d\n",b);
}
void zoo() {
int dummy = 7;
}
void bar(){
int a1=3;
}
int main(){
bar();
zoo();
foo();
return 0;
}
Ref: Doc