What happens if a function returns but i take the address of it's local variable?

Jun 2, 2014 at 6:29pm

I don't understand how this program is still able to give correct output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  
#include <stdio.h>

int* fun();

int main()
{
    int *j,d =5;
    j = fun();
    printf("%d\n",d);//If I comment this statement then the program gives //correct ouput for k i.e. 35, but if this line stays it gives garbage value 
    printf("%d\n",*j);
    return 0;
}


int *fun()
{
    int k  = 35;
    return (&k);
}


If I comment the above given statement printf("%d\n",d) then the program gives correct ouput for k i.e. 35, but if this line stays it gives garbage value.
What's up with that?
Jun 2, 2014 at 6:49pm
Jun 2, 2014 at 6:54pm
When you call fun() at line 9, fun() allocates local storage for k. When fun() exits, k goes out of scope and it is no longer legal to reference what was at the local where k was stored. However, depending on machine architecture and compiler optimization, when fun() returns, the location where k was stored may not necessarily be overwritten. When printf is called at line 10, printf will allocate it's own local storage. Simply allocating that local storage won't necessarily overwrite the address where k was stored. However, when printf writes to its local storage it very well may overwrite the storage where k was stored.

edit: In any case, as Cubbi stated, the behavior is undefined.
Last edited on Jun 2, 2014 at 6:55pm
Topic archived. No new replies allowed.