Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how about .bss section not zero initialized

Tags:

c

gcc

elf

as we know .bss contains un-initialized variables. if in c code, programer initialize the variables before using them. then .bss is not necessary to be zero before executing C code.

Am I right?

Thanks

like image 921
richard Avatar asked Nov 28 '22 19:11

richard


2 Answers

In C code, any variable with static storage duration is defined to be initialized to 0 by the spec (Section 6.7.8 Initialization, paragraph 10):

If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.

Some program loaders will fill the whole section with zeroes to start with, and others will fill it 'on demand' as a perfomance improvement. So while you are technically correct that the .bss section may not really contain all zeroes when the C code starts executing, it logically does. In any case, assuming you have a standard compliant toolchain, you can think of it as being all zero.

Any variables that are initialized to non-zero values will never end up in the .bss section; they are handled in the .data or .rodata sections, depending on their particular characteristics.

like image 126
Carl Norum Avatar answered Dec 04 '22 12:12

Carl Norum


The ELF specification says:

.bss This section holds uninitialized data that contribute to the program’s memory image. By definition, the system initializes the data with zeros when the program begins to run. The section occupies no file space, as indicated by the section type, SHT_NOBITS.

It therefore follows that a C global variable which has a value assigned to it cannot be put into the .bss section and will have to go into the .data section. The .data section contains the initial valued for all the variables assigned to it.

like image 24
doron Avatar answered Dec 04 '22 11:12

doron