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()
?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With