分类: WINDOWS
2010-11-05 10:47:46
C语言的函数调用
一,一个简单的C程序
#include "stdafx.h"
int max(int a,int b)
{
return (a>b)?a:b;
}
int main(int argc, char* argv[])
{
int maxer;
maxer = max(5,6);
printf("maxer=%d\n",maxer);
return 0;
}
这个程序简单的无话可说,只是想看看一些东西,所以越简单越好!
二,反汇编看看,可以看到,如此简单的程序到现在竟然如此庞大!
1: // test.cpp : Defines the entry point for the console application.
2: //
3:
4: #include "stdafx.h"
5:
6: int max(int a,int b)
7: {
00401020 push ebp //栈底指针入栈
00401021 mov ebp,esp //ebp = esp,可以理解为建立新栈
00401023 sub esp,44h //申请一部分内存
00401026 push ebx
00401027 push esi
00401028 push edi //以上三个寄存器入栈
00401029 lea edi,[ebp-44h]
0040102C mov ecx,11h
00401031 mov eax,0CCCCCCCCh
00401036 rep stos dword ptr [edi]
//初始化变量,debug版默认初始为0xcc,这就是调试时会发现很多“烫”的原因
8: return (a>b)?a:b;
00401038 mov eax,dword ptr [ebp+8]
0040103B cmp eax,dword ptr [ebp+0Ch]
0040103E jle max+28h (00401048)
00401040 mov ecx,dword ptr [ebp+8]
00401043 mov dword ptr [ebp-4],ecx
00401046 jmp max+2Eh (0040104e)
00401048 mov edx,dword ptr [ebp+0Ch]
0040104B mov dword ptr [ebp-4],edx
0040104E mov eax,dword ptr [ebp-4]
9: }
00401051 pop edi
00401052 pop esi
00401053 pop ebx //出栈返回
00401054 mov esp,ebp //恢复栈项指针,可以理解为子函数栈的销毁
00401056 pop ebp //回到调用函数的栈
00401057 ret //恢复
10: int main(int argc, char* argv[])
11: {
00401070 push ebp
00401071 mov ebp,esp
00401073 sub esp,44h
00401076 push ebx
00401077 push esi
00401078 push edi
00401079 lea edi,[ebp-44h]
0040107C mov ecx,11h
00401081 mov eax,0CCCCCCCCh
00401086 rep stos dword ptr [edi] //这些跟上面那个函数一样,不需要再解释
12: int maxer;
13: maxer = max(5,6);
00401088 push 6
0040108A push 5
0040108C call @ILT+0(max) (00401005)//通过栈调用子函数max
00401091 add esp,8
00401094 mov dword ptr [ebp-4],eax //eax就是子函数返回值
14: printf("maxer=%d\n",maxer);
00401097 mov eax,dword ptr [ebp-4]
0040109A push eax
0040109B push offset string "maxer=%d\n" (0042001c)
004010A0 call printf (004010d0)
004010A5 add esp,8
15: return 0;
004010A8 xor eax,eax
16: }
004010AA pop edi
004010AB pop esi
004010AC pop ebx
004010AD add esp,44h
004010B0 cmp ebp,esp
004010B2 call __chkesp (00401150)//这个是编译器加的检查栈函数
004010B7 mov esp,ebp
004010B9 pop ebp
004010BA ret
chinaunix网友2010-11-05 14:49:02
很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com