【发布时间】:2016-01-15 01:25:16
【问题描述】:
据我所知,未显式初始化的静态变量(对于 GCC,即使设置了 -fzero-initialized-in-bss,即使是那些显式初始化为零的变量,默认情况下也是如此)通常存储在BSS 段。然而,似乎当我尝试检查该行为时,这些变量存储在通用数据部分(具有初始化的全局变量)。如果我编译(使用-O0 进行很好的衡量)并运行:
#include <stdio.h>
#include <stdlib.h>
extern char etext, edata, end;
int i = 42;
int main(int argc, char* argv[])
{
static int j;
printf ("end of program (etext) = %10p\n",&etext);
printf ("end of initialized data (edata) = %10p\n",&end);
printf ("end of uninitialized data (end) = %10p\n",&end);
printf ("=====\n");
printf ("Value of i (initialized global) : %d\n",i);
printf ("Address of i : %10p\n",&i);
printf ("Value of j (static with no explicit initialization) : %d\n",j);
printf ("Address of i : %10p\n",&j);
return 0;
}
我得到了输出:
end of program (etext) = 0x40067d
end of initialized data (edata) = 0x600af0
end of uninitialized data (end) = 0x600af0
=====
Value of i (initialized global) : 42
Address of i : 0x600ae0
Value of j (static with no explicit initialization) : 0
Address of i : 0x600ae8
所以i 和j 存储在&etext 和&edata 之间的连续内存地址,这是常规数据部分。此外,&edata == &end 似乎意味着 BSS 是空的。
现在我意识到编译器将哪个变量放在哪里是一个实现选择,它产生的结果是正确的。但我只是想知道为什么我会出现这种行为,以及是否有办法告诉 gcc 明确地将这些变量放在 BSS 中(我在手册中没有看到任何明显的解决方案)。
【问题讨论】:
-
您的代码为 edata 和 end 打印 &end,这是复制粘贴问题还是造成这种混乱的原因?