Activation Record In GNU C (Nested Function)
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; <------开发者_JAVA技巧------------ 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?
At point p, there are 4 activation records on the stack:
activation record for g:
- return address to f
- static link to h activation record
- z =
12
activation record for f:
- x =
4
- return address to h
- static link to h activation record
- y =
3
activation record for h:
- x =
1
- return address to main
activation record for main:
- a = undefined
- return address to OS
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.
I think that at point P, x
can only refer to the x
defined in h()
; it could only refer to the x
in g()
if it were itself nested inside g()
.
精彩评论