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

问题描述 投票:1回答:1

假设此代码:

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的堆栈中?

让我们假设这些值是按钉书钉而不是寄存器。

c assembly calling-convention
1个回答
1
投票

这取决于体系结构和调用约定。在x86-32中,几乎所有调用约定在64位结果中的返回值都在eaxedx:eax中。因此,您的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中,因此不需要额外的工作。

那就是说,除非您询问特定的体系结构,否则您将不会找到“一般情况”的答案,即使那样,它上可能会有多种不同的调用约定。

© www.soinside.com 2019 - 2024. All rights reserved.