top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How a function can access value of local variable of another function whose stack is already gone?

+5 votes
575 views

Even I have similar problem:

int (*pfun)(void);
int *pInt = 0;
void fun1()
{
    int i = 5; /* Local to fun1*/

    printf("Outer function");
    pInt = &i; /* As I know address of local variable is valid till function execution */

    int fun2()
    {
      printf("innerfunction");
      printf("%d", *pInt);
    }
    /* fun2 address assign to pfun so that It can be called even after completion of fun1 */
    pfun = fun2;
}

int main()
{
    fun1();
    pfun();
    return 0;
}

Can someone please explain ? I am getting *pInt value 5.

posted Oct 14, 2013 by Vimal Kumar Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+4 votes

1) Because address space for stack is not overwritten. So you are getting the same same value "5".
2) Stack got memory form heap, heap exist in address space of that process.

If you want to access the local variable.
Declare the local variable as static. Static variables goes in data section.
Now you can store the address of these static variables in global pointers
OR you can return address of variable.

Please correct if I am wrong.

answer Oct 14, 2013 by Vikas Upadhyay
Is this behavior consistence for all the system ?
Similar Questions
+4 votes

in case if is it possible, how you can change and pls explain with some example.

+1 vote

in the following code func.c :

 int Myfunc1(int i, int z)
 {
 return i;
 }

 int main()
 {
 int ans;

 /* casting the function into an 'int (int)' function */
 ans = ((int(*)(int))(Myfunc1))(5);

 printf("ans: %dnn", ans);

 return 0;
 }

I tried to cast an int(int,int) function into an int(int) function an got the gcc warning and note:

 func.c:13:32: warning: function called through a non-compatible type [enabled by default]
 func.c:13:32: note: if this code is reached, the program will abort

and when trying to run I get:

 Illegal instruction (core dumped)

But if i compile this file with a .cpp ending with the gcc compiler it works OK.

+2 votes

Please share a sample program with detail code.

...