The following happens:
- Within
func1
, you created the localx
variable and initialised it with a value, i.e.x
is on the stack now. - You get the address of
x
and return it tomain
. - While returning,
func1
and its variablesx
(and, irrelevant to the question,y
) arefree
d, or popped off the stack, i.e. their memory locations are not reserved any more to hold their values. After this, any other part of the program is allowed to use the memory space that was allocated forx
withinfunc1
, asfunc1
isn’t active any more. - Your first
printf
call still happens to see the old value of the memory location wherex
used to be (but this is not guaranteed) and - the second
printf
call makes it apparent that something else (with the value of 0, such as the firstprintf
‘s return value as described by R. Joiny) is (or was) using the same address asx
withinfunc1
.
This article of the C Programming Boot Camp pretty much describes your situation:
A key to understanding the stack is the notion that when a function
exits, all of its variables are popped off of the stack (and hence
lost forever). Thus stack variables are local in nature. This is
related to a concept we saw earlier known as variable scope, or local
vs global variables. A common bug in C programming is attempting to
access a variable that was created on the stack inside some function,
from a place in your program outside of that function (i.e. after that
function has exited).