函数调用栈

函数调用栈

首先看一个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
using namespace std;
int sum(int a,int b)
{
int temp=0;
temp=a+b;
return temp;
}
int main()
{
int a=10;
int b=20;
int ans=sum(a,b);
cout<<"ans:"<<ans<<endl;
return 0;
}

main函数调用sum,sum执行完之后,怎么知道回到那个函数?

sum函数执行完,回到main以后,怎么知道从哪一行指令继续运行?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
using namespace std;
int sum(int a,int b)
{
/*
这块是有指令生成的,在第一个花括号到int temp之间
push ebp
mov ebp,esp
sub esp,4Ch
*/
int temp=0;//mov dword ptr[ebp-4],0
temp=a+b;//mov eax,dword ptr[ebp+0Ch] add eax,dword ptr[ebp-8] mov dword ptr[ebp-4],eax
return temp;//mov eax,dword ptr[ebp-4]
/*
mov esp,ebp
pop ebp
*/
}
int main()
{
int a=10;//mov dword ptr[ebp-4],0Ah
int b=20;//mov dword ptr[ebp-8],14h
int ans=sum(a,b);
/*
mov eax,dword ptr[ebp-8]
push eax
mov eax,dword ptr[ebp-4]
push eax
call sum{
add esp,8
mov dword ptr[ebp-0Ch],eax
}
*/
cout<<"ans:"<<ans<<endl;
return 0;
}