C和C++的存储模式
测试环境:winxp TC2.0 VC++6.0
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = 0x1234;
int j = 0x5678;
printf("i = %x \n",i);
printf("j = %x \n",j);
printf("main = %x",main);
scanf(&i,&j);
return 0;
}
int main(int argc, char *argv[])
{
int i = 0x1234;
int j = 0x5678;
printf("i = %x \n",i);
printf("j = %x \n",j);
printf("main = %x",main);
scanf(&i,&j);
return 0;
}
对应的汇编代码:
var_i= byte ptr -4
var_j= word ptr -2
argc= word ptr 4
argv= dword ptr 6
envp= dword ptr 0Ah
push bp
mov bp, sp
sub sp, 4
mov word ptr [bp+var_i], 1234h
mov [bp+var_j], 5678h
push word ptr [bp+var_i]
mov ax, 194h
var_j= word ptr -2
argc= word ptr 4
argv= dword ptr 6
envp= dword ptr 0Ah
push bp
mov bp, sp
sub sp, 4
mov word ptr [bp+var_i], 1234h
mov [bp+var_j], 5678h
push word ptr [bp+var_i]
mov ax, 194h
从上面的汇编代码可以看出,在C中先定义的变量,在栈中的地址是比较低的,后定义的变量栈中地址高。
在VC6.0中
int a = 0x12345678;
int b = 0x1234;
int b = 0x1234;
汇编代码
6: int i = 0x1234;
00401028 mov dword ptr [ebp-4],1234h
7: int j = 0x5678;
0040102F mov dword ptr [ebp-8],5678h
00401028 mov dword ptr [ebp-4],1234h
7: int j = 0x5678;
0040102F mov dword ptr [ebp-8],5678h
mov [ebp+var_24], 12345678h ; a
mov [ebp+var_28], 1234h ; b
mov [ebp+var_28], 1234h ; b
结论:在VC6.0里面C++和C中,先申请的变量地址高,后申请的地址低,类似于先申请的先入栈,后申请的后入栈。
这个貌似和编译器有关。
学习,积累中......