gpt4 book ai didi

c - C语言中被调用(派生)函数如何访问调用者(基)函数的变量?

转载 作者:行者123 更新时间:2023-11-30 16:52:02 26 4
gpt4 key购买 nike

考虑以下代码:

void foo(){
.....
}
int main()
{
int arr[3][3] ;
char string[10];
foo();
return 0;
}

函数 foo 如何访问主函数的局部变量而不将参数作为函数参数传递给函数?函数 foo 是否有足够的权限来访问和修改 main 中的变量?请回复谢谢你

最佳答案

根据 C 语言规范,其他函数无法访问函数的局部变量。没有合法的、受支持的方法来完成您所要求的操作。也就是说,在大多数(全部?)C 语言的实现中,主函数的变量将存储在堆栈中,这很容易定位并且任何人都可以读写(这必须是因为每个人都需要存储本地信息)在其中)所以这在技术上是可行的(尽管这是一个非常糟糕的主意)。

void foo(){
int b; // puts a 4 byte word on the stack atop the return address
(&b)[2]; // interpret b as the first entry in an array of integers (called the stack)
// and offset past b and the return address to get to a
// for completeness
(&b)[0]; // gets b
(&b)[1]; // gets the return address
}
int main()
{
int a; // puts a 4 byte word on the stack
foo(); // puts a (sometimes 4 byte) return address on the stack atop a
return 0;
}

在某些系统(如 32 位 x86 系统)上,此代码可能会访问主函数内部的变量,但它很容易被破坏(例如,如果该系统上的指针是 8 个字节,如果堆栈上有填充) ,如果使用堆栈金丝雀,如果每个函数中有多个变量,并且编译器对于它们应该采用的顺序有自己的想法,等等,则此代码将无法按预期工作)。所以不要使用它,使用参数,因为没有理由不这样做,而且它们有效。

关于c - C语言中被调用(派生)函数如何访问调用者(基)函数的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41420983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com