GNU C 中的激活记录(嵌套函数)
在GNU C中,结果是13。因为使用了静态链接。
否则,如果使用动态链接,结果将为 16。
#include <stdio.h>
int h(){
int x = 1;
int g(int z){
return z + x; <------------------ P
}
int f(int y){
int x = y + 1;
return g(x * y);
}
return f(3);
}
int main(){
int a = h();
printf("%d\n", a);
}
在 P 点,激活记录为
z = 12
x = 4
y = 3
f 和指向代码 f
g 的指针和指向代码 g 的指针
x = 1
h 和指针代码 h 为
main
并指向代码 main
是这样吗?
但是如果函数 g 返回,情况如何?
g 的激活和变量 z 的激活被删除。
然后在堆栈帧中,查看漏洞。这个洞真的出现了吗?
并且根据 In-line 块,在函数 h 中,
变量 x 是最外层的块。 (这意味着函数 g' 块嵌套在变量 x 的块中) 下一个外部块是函数 g,下一个函数 f... 那么,函数f的静态链接是否指向函数g的帧指针? 或者函数h的帧指针? 函数 g 的静态链接怎么样?
In GNU C, The Result is 13. Because the static link is used.
Otherwise, If the dynamic link is used, the result would be 16.
#include <stdio.h>
int h(){
int x = 1;
int g(int z){
return z + x; <------------------ P
}
int f(int y){
int x = y + 1;
return g(x * y);
}
return f(3);
}
int main(){
int a = h();
printf("%d\n", a);
}
At the P point, Activation Record is
z = 12
x = 4
y = 3
f and pointer to code f
g and pointer to code g
x = 1
h and pointer to code h
a
main and pointer to code main
Is that right?
However if function g returns, how is it going?
The Activation for g and Activation for variable z is deleted.
Then In stack frame, The hole is looked.The hole really appear?
And According to In-line block, In function h,
variable x is the most outer block. (It means that function g' block is nested in variable x's block)
next outer block is function g, next function f...
Then, Do function f's Static link point to function g's frame pointer?
Or function h's frame pointer?
What about function g's Static link?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 p 点,堆栈上有 4 个激活记录:
g 的激活记录:
12
f 的激活记录:
4< /code>
3
h 的激活记录:
1
main 的主激活记录地址:
嵌套的每个激活记录函数包含一个到词法封闭激活记录(这里两种情况下都是 h)的链接,该链接是在调用函数并创建激活记录时设置的。在点 p 处,代码将取消引用该链接以查找 x 的值,并且查看此类链接是函数查看其他函数的激活记录的唯一一次。
At point p, there are 4 activation records on the stack:
activation record for g:
12
activation record for f:
4
3
activation record for h:
1
activation record for main:
Each activation record for a nested function contains a link to the lexically enclosing activation record (h in both cases here) which is set up when the function is called and the activation record is created. At point p, the code will dereference that link to find the value of x, and looking through such links is the ONLY time a function will ever look at some other function's activation record.
我认为在P点,
x
只能引用h()
中定义的x
;如果它本身嵌套在g()
中,它只能引用g()
中的x
。I think that at point P,
x
can only refer to thex
defined inh()
; it could only refer to thex
ing()
if it were itself nested insideg()
.