Reputation: 2593
I am trying to modify the value of local variable through another called function, but I am not able to figure out what all values pushed onto the stack are.
#include <stdio.h>
#include <string.h>
void fun()
{
int i;
int *p=&i;
int j;
for(j=0;*(p+j)!=10;j++);
printf("%d",j);
/* Stack Frame size is j int pointers. */
*(p+j)=20;
}
main()
{
int i=10;
fun();
printf("\n %d \n",i);
}
How exactly does j
in fun()
equal to 12
? I am trying to understand what values are pushed onto stack. More specifically, can we change the value of i
which is in main()
without using a for
loop in fun()
and is it possible to predict the value of j
inside fun()
?
Upvotes: 9
Views: 573
Reputation: 1261
When you have to access local variables from other function calls, I think you had better redesign your code.
Theoretically, you can direct to modify the i
of main()
in fun()
if you can completely understand how the compilers deal with the activation records of function calls on the run-time stack. You can read "Compilers: Principles, Techniques, and Tools" for details( http://www.amazon.com/Compilers-Principles-Techniques-Tools-Edition/dp/0321486811 )
The value of j depends on the run-time stack address between the int i;
in the fun() and int i = 10;
in main() . In this case, when fun() is called, their relative distance on stack is just 12. That is why the j
is 12. So the *(p + j) = 20;
actually changed the i
of the main(). If you change your code by adding int a = 14;
as following, you will find the value of j
changed for the activation record on the run-time stack has been changed.
#include <stdio.h>
void fun()
{
int i;
int *p=&i;
int j;
for(j=0;*(p+j)!=10;j++);
printf("%d",j);
/* Stack Frame size is j int pointers. */
*(p+j)=20;
}
main()
{
int i=10;
int a=14; /* add this for example to change the relative address i in the main and i in the fun*/
fun();
printf("\n %d \n",i);
}
Upvotes: 3
Reputation: 736
Here in fun()
In the for loop j is initially 0 and the for loop will run until the value in the address p+j !=10
and j is incremented.
So there is no way to correctly predict the outcome of the print in fun()
and also before getting out of the fun()
you are trying to assign 20 to the memory location p=j
where j could be any value [0,+infinity)
no way of telling correctly
meanwhile the print func in main() will display value of local i that is 10 that is if the address of this i in main() in not equal to p+j
Upvotes: 0