c语言中被调用(派生)函数如何访问调用者(基)函数的变量?
How can the called (derived) function access the variables of the caller (base) function in c language?
考虑以下代码:
void foo(){
.....
}
int main()
{
int arr[3][3] ;
char string[10];
foo();
return 0;
}
函数 foo 如何在不将参数作为函数参数传递给函数的情况下访问我的 main 函数的局部变量?函数 foo 是否有足够的权限访问和修改 main 中的变量?
请回复
谢谢
根据 C 语言规范,其他函数无法访问一个函数的局部变量。没有合法的、受支持的方式来做你所要求的。也就是说,在大多数(所有?)C语言的实现中,main函数的变量都会存储在栈中,这样很容易定位,任何人都可以读写(一定是因为每个人都需要存储本地信息在里面)所以它在技术上是可行的(尽管这是一个非常糟糕的主意)。
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 个字节,如果有填充堆栈,如果正在使用堆栈金丝雀,如果每个函数中有多个变量,并且编译器对它们的顺序有自己的想法,等等,则此代码将无法按预期工作)。所以不要使用它,使用参数,因为没有理由不这样做,而且它们有效。
考虑以下代码:
void foo(){
.....
}
int main()
{
int arr[3][3] ;
char string[10];
foo();
return 0;
}
函数 foo 如何在不将参数作为函数参数传递给函数的情况下访问我的 main 函数的局部变量?函数 foo 是否有足够的权限访问和修改 main 中的变量? 请回复 谢谢
根据 C 语言规范,其他函数无法访问一个函数的局部变量。没有合法的、受支持的方式来做你所要求的。也就是说,在大多数(所有?)C语言的实现中,main函数的变量都会存储在栈中,这样很容易定位,任何人都可以读写(一定是因为每个人都需要存储本地信息在里面)所以它在技术上是可行的(尽管这是一个非常糟糕的主意)。
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 个字节,如果有填充堆栈,如果正在使用堆栈金丝雀,如果每个函数中有多个变量,并且编译器对它们的顺序有自己的想法,等等,则此代码将无法按预期工作)。所以不要使用它,使用参数,因为没有理由不这样做,而且它们有效。