This question already has answers here:
Closed 7 years ago.
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
input:
#include <stdlib.h>
#include <stdio.h>
int func2(void);
int* func1(void);
int func2(void)
{
int* b;
b = func1();
printf("%d", *b);
printf("%d", *b);
printf("%d", *b);
}
int* func1()
{
int a = 13;
return &a;
}
int main()
{
func2();
}
Output:
13 -1077824828 -1077824828
Can someone explain what happened in the stack and OS? Why the result changed from 13 to garbage after getting the value of the pointer?
Sure.
The result will differ between debug and release (clean).
A local variable is EBP-(some offset) if you look at the assembly.
This means, HIGHER IN STACK, as in "further".
This is the address you return.
Normally it would be untouched if the function just returns. In debug build on some compilers, it would be garbaged on purpose to help you catch the dangling pointer error faster. Now, printf call reuses the same addresses in the stack to pass parameters and for its own local variables (it has some). They will be written to the address emptied by func1 return, thus overwriting whatever is pointed by the address you obtained.
Calling printf creates a new stack frame that overwrites the location previously occupied by a
.