gpt4 book ai didi

c - 如何使用堆栈从函数返回值

转载 作者:行者123 更新时间:2023-12-04 10:28:47 27 4
gpt4 key购买 nike

假设这段代码:

int add(int a, int b){
int c = a+b;
return c;
}

int main(){
printf("%d\n", add(3,4));
}

以下通常是在汇编中实现的方式:
- push 4 to stack
- push 3 to stack
- push return address which is the address of the next instruction, `print()` to stack
- call add
- do addition and push c on the stack
- pop c from stack ??
- return to main

那么返回值怎么办,不能在 add上帧,因为它会在最后被清除。它是否被放入 main 的堆栈中? ?

让我们假设这些值被推送到大头钉而不是寄存器。

最佳答案

这取决于体系结构和调用约定。在 x86-32 中,几乎每个调用约定都有返回值 eaxedx:eax对于 64 位结果。所以你的 add函数可能有说明:

mov eax, dword ptr [esp+4] ; put 1st arg in eax
add eax, dword ptr [esp+8] ; add eax with 2nd arg
ret ; return

不需要额外的工作,因为返回值已经应该在 eax 中。 .

也就是说,除非您询问特定的架构,否则您不会为此找到“一般情况”的答案,即使如此,可能会有多种不同的调用约定。

关于c - 如何使用堆栈从函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60509178/

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