关于BSS段的大小问题

在SHLUG上有人提出个问题,如下:

《C专家编程》书上119页有这么一句话:由于BSS段只保存没有值的变量,所以事实上它并不需要保存这些变量的映像。运行时所需要的BSS段的大小记录在目标文件中,但BSS段并不占据目标文件的任何空间

我做了下实验:
$cat hello.c
int a[1000];
int main()
{
    printf("Hello, world!\n");

    return 0;
}

$gcc hello.c
$size a.out

  text           data     bss     dec     hex filename
  1129     504    4032    5665    1621 a.out

 按照书上所讲数组a应该是保存在bss段的,但是" 它并不需要保存这些变量的映像", 那为什么bss段会有大小?怎么理解" 它并不需要保存这些变量的映像"这句话?

我查了一些资料,我觉的这个问题可以这样解释。
在《程序员的自我修养》一书中,作者对BSS段的描述是:“ BSS段存放的是未初始化的全局变量和局部变量。。。 其实更准确的说法是
BSS段为它们预留了空间”。(在第66页)
 
然后,我们来看ELF的说明文档中的原话:
.bss This section holds uninitialized data that contribute to the program's memory image. By definition, the system initialize the
data with zeros when the program begins to run. The section occupies no file space, as indicated by the section type, SHT_NOBIT。
BSS段的类型是SHT_NOBIT,其属性是SHF_ ALLOC+SHF_WRITE。
先来看看ELF文 档对SHT_NOBIT类型的描述和对SHF_ALLOC、 SHF_WRITE的描述:
SHT_NOBIT    A section of this type occupies no space in the file but otherwise resembles SHT_PROGBITS. Although this section contains no bytes, the sh_offset member contains the conceptual file offset.
SHF_WRITE    The section contains data that should be writable during process execution.
SHF_ALLOC    The section occupies memory during process execution. Some control section do not reside in the memory image of an object file; this attribute is off for those sections.
 
到这里,可以得出如下结论了:
(1)《程序员的自我修养》一书中的相关的描述是不恰当的, 至少是会让人产生误解的,而你看到的《专家编程》 中的话是比较靠谱的
(2)你用size命令查看到的bss段的所谓的大小, 也只是个“大小”而已,在文件中不会有它实际的空间, 只有该文件被装载执行的时候,
         才会被分配内存,并且初始化为0。( 你可以做个试验,你可以看一下现在你的hello.o的大小, 然后将你的数组的长度加大10倍,再看一下
        hello.o的大小,看有没有什么变化)
(3)至于bss段下面显示的“大小”,“the sh_offset member contains the conceptual file offset”这句话就可以解释啦!


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值