gpt4 book ai didi

c++ - vs2010中的变量排列

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:56:51 24 4
gpt4 key购买 nike

代码://VS2010

int a;
int b;
int c;
int d;

int main(){
//output the address of global variables
printf("0x%x, 0x%x, 0x%x, 0x%x\n", &a, &b, &c, &d);

int a1, b1, c1, d1;
//output the address of local variables
printf("0x%x, 0x%x, 0x%x, 0x%x\n", &a1, &b1, &c1, &d1);

int a2 = 1;
int b2 = 2; int c2; int d2 = 4;
//output the address of local variables
printf("0x%x, 0x%x, 0x%x, 0x%x\n", &a2, &b2, &c2, &d2);
}

输出:

0x1197a44, 0x1197a3c, 0x1197a40, 0x1197a38
0x15fb00, 0x15faf4, 0x15fae8, 0x15fadc
0x15fad0, 0x15fac4, 0x15fab8, 0x15faac

我的问题:

  1. 为什么全局变量没有按顺序存储?上面的输出表示它们是乱序的。

  2. 为什么局部变量没有连续存储?上面的输出表示VS2010在每两个之间插入了8个字节的空间。

有人能帮帮我吗?非常感谢!

----------------------------------------补全-------- ------------------------------------

代码:\gcc 版本 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3)

int a;
int b;
int c;
int d;

void main(){
//output the address of global variables
printf("%p, %p, %p, %p\n", &a, &b, &c, &d);

int a1, b1, c1, d1;
//output the address of local variables
printf("%p, %p, %p, %p\n", &a1, &b1, &c1, &d1);

int a2 = 1;
int b2 = 2; int c2; int d2 = 4;
//output the address of local variables
printf("%p, %p, %p, %p\n", &a2, &b2, &c2, &d2);
}

输出:

0x60103c, 0x601034, 0x601038, 0x601030
0x7fff126253a0, 0x7fff126253a4, 0x7fff126253a8, 0x7fff126253ac
0x7fff126253b0, 0x7fff126253b4, 0x7fff126253b8, 0x7fff126253bc

在gcc中,全局变量和局部变量的地址是连续的、有序的。

所以我想知道 vs2010 为我们的代码做了什么以及为什么这样做。

最佳答案

它们都不是规范指定的,编译器可以做它想做的。

至于局部变量,您可能正在使用 DEBUG 构建,并插入填充以检查堆栈完整性。如果发生任何内存溢出,填充将被覆盖并发现溢出。

关于c++ - vs2010中的变量排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8515544/

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