【发布时间】:2020-04-19 12:50:50
【问题描述】:
假设这个 C 代码:
int add(int a, int b){
int c = a+b;
return c;
}
int main(){
int c = add(3,4);
printf("%d", c);
return 0;
}
当调用add 时会发生以下情况:
Push 4 on the stack
Push 3 on the stack
Push the address of `printf` on the stack (return address)
call `add`
// do stuff under add
pop the stack and and goto `printf`
但add 下的值 4 和 3 仍在堆栈-0x18(%rbp) 上。他们不应该被清除吗?
00000000000005fa <add>:
5fa: 55 push %rbp
5fb: 48 89 e5 mov %rsp,%rbp
5fe: 89 7d ec mov %edi,-0x14(%rbp)
601: 89 75 e8 mov %esi,-0x18(%rbp)
604: 8b 55 ec mov -0x14(%rbp),%edx
607: 8b 45 e8 mov -0x18(%rbp),%eax
60a: 01 d0 add %edx,%eax
60c: 89 45 fc mov %eax,-0x4(%rbp)
60f: 8b 45 fc mov -0x4(%rbp),%eax
612: 5d pop %rbp
613: c3 retq
0000000000000614 <main>:
614: 55 push %rbp
615: 48 89 e5 mov %rsp,%rbp
618: be 04 00 00 00 mov $0x4,%esi
61d: bf 03 00 00 00 mov $0x3,%edi
622: e8 d3 ff ff ff callq 5fa <add>
627: 5d pop %rbp
628: c3 retq
【问题讨论】:
-
4 和 3 被放入寄存器 ESI 和 EDI,而不是堆栈。
-
查看
-
你认为他们为什么会被清除?没有标准甚至惯例要求这样做。一个实现当然可以做到这一点,但大多数都做不到,因为那会很昂贵。
-
我无法想象“添加”出来,SP 在哪里降低到局部变量之下?
-
@Jasen,编译器正在利用“红色区域”。 en.m.wikipedia.org/wiki/Red_zone_(computing)