Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
What’s the problem with the second printf?
#include<stdio.h>
int* fun() {
int a =10;
return &a;
}
int main() {
int *a;
a = fun();
printf("%d",*a);
printf("%d",*a);
return 0;
}
I have returned the address of local variable and passed it to the printf. The first time it prints correctly as “10”, but the second time it shows a junk value.
If initially a was a dangling pointer pointing to address of 10, why doesn’t it the second time?
Can anyone explain this?
I even tried calling some other function before calling printf the first time but I still get the same output.
After BeniBela’s ans i tried wit this..
#include<stdio.h>
int* fun()
{
int a =10;
return &a;
}
void fun2(int d)
{
int a,b,c;
}
int main()
{
int *a,b;
a = fun();
fun2(5);
printf("%d",*a);
printf("%d",*a);
return 0;
}
still same output..:(
What actually happens is:
All local variables are stored on the stack.
Before the call to fun, the stack contains only the *a variable of main, like:
|int *a = undefined||When fun is called, the parameters to fun (i.e. none), the address to main and the local variables of fun are added to the stack:
|int *a = undefined| return to main | int a = 10 ||(there is also the frame pointer but that doesn’t matter)After fun returns, the stack is
|int *a = 2nd next stack var|| return to main | int a = 10 |. The last 2 stack variables are invalid, but they are still there.When the first printf is called the parameters to printf (in inverse order *a then” %d”), the return address and the local variables of printf are added again after *a and override the old values:
It first becomes
|int *a = 2nd next stack var| int a = 10 || inta = 10 |
then
|int *a = 2nd next stack var| int a = 10 | "%d" |then
|int *a = 2nd next stack var| int a = 10 | "%d" | return tomain ||
and finally
|int *a = 2nd next stack var| int a = 10 |"%d" | return to main | local vars of printf ||
[edit:]
The fun2 does not override the 10 on the stack, because gcc reserves empty bins on the stack, where the arguments of called functions are put. So it is not
|int *a = 2nd next stack var| return to main | int a = 10 |as I wrote above, but more like|int *a = 4th next stack var | empty | empty | return to main | int a = 10 |.When fun2 is called, it becomes
|int *a = 4th next stack var | empty | 5 | return to main | int a = 10 |, and the 10 is still not overriden.The
int *a,b,cwithin the function do not matter, since they do not have a value assigned.With gdb you can look at the actual stack (it grows backward):
Before fun:
After fun, before fun2 and its arguments:
After fun2: