Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What values are pushed onto stack during a function call?

Tags:

c

pointers

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()?

like image 691
debonair Avatar asked Oct 29 '14 03:10

debonair


1 Answers

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 )

enter image description here

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);
}
like image 71
Yulong Ao Avatar answered Sep 30 '22 16:09

Yulong Ao