c - 在函数调用期间将哪些值压入堆栈?

标签 c pointers

我试图通过另一个调用的函数修改局部变量的值,但我无法弄清楚压入堆栈的所有值是什么。

#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);
}

j到底是怎么回事?在fun()等于12 ?我试图了解哪些值被压入堆栈。更具体地说,我们可以更改 i 的值吗?这是在 main()不使用 for循环 fun()是否有可能预测 j 的值里面fun()

最佳答案

当您必须从其他函数调用访问局部变量时,我认为您最好重新设计代码。

理论上,如果你完全理解编译器是如何处理的,你可以直接修改fun()main()i与运行时堆栈上函数调用的激活记录。详情可以阅读《Compilers: Principles, Techniques, and Tools》(http://www.amazon.com/Compilers-Principles-Techniques-Tools-Edition/dp/0321486811)

enter image description here

j 的值取决于 fun() 中的 int i; 和 main() 中的 int i = 10; 之间的运行时堆栈地址。在这种情况下,当调用 fun() 时,它们在堆栈上的相对距离仅为 12。这就是 j 为 12 的原因。因此 *(p + j) = 20; 实际上改变了 main() 的 i。如果您通过如下添加 int a = 14; 来更改代码,您会发现 j 的值已更改,因为运行时堆栈上的激活记录已更改.

#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);
}

关于c - 在函数调用期间将哪些值压入堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26622424/

相关文章:

c - 循环遍历 C 中的 char 指针

c++ - 如何在动态矩阵中创建主键

c - 如何判断一个socket被另一个线程shutdown()?

c - 如何从 addrinfo 获取 sin6_addr?

C 程序吃掉了我所有的 RAM+SWAP 资源

C++:返回子类指针

c++ - Lambda函数引用指针销毁检测

c - 指针、数组和传递指针到方法

c++ - 是否可以在 C++ 中对 C 结构进行子类化并在 C 代码中使用指向该结构的指针?

c++ - Linux上的C/C++多线程服务器/客户端崩溃