3

I understand that the default alignment of .bss is 8 bytes for GCC as mentioned in this question Why the int type takes up 8 bytes in BSS section but 4 bytes in DATA section

So with this program:

int main(){
    
    return 0;
}

I have something like this:

   text    data     bss     dec     hex filename
   1418     544       8    1970     7b2 test

When I add an static variable with initialization to increase .data (and it does):

static int var = 255;

int main(){
    
    return 0;
}

I see that the size of .bss also decrease 4 bytes:

  text     data     bss     dec     hex filename
  1418      548       4    1970     7b2 test

Please tell me why ?

Van Tr
  • 5,889
  • 2
  • 20
  • 44
  • 2
    .bss should't take any memory. I guess this behavior maybe due to alignment. It is dependent on compiler implementation. – Raman Jan 02 '20 at 11:27
  • Have you tried looking at output from `readelf`, `nm`, etc. to see if you can determine what symbols are at the address[es] in bss? – R.. GitHub STOP HELPING ICE Jan 02 '20 at 16:25
  • @R..GitHubSTOPHELPINGICE yes, I did, I am looking at the default linker file of gcc also, since I am using the default linker file. I think it's from the way of alignment between `.bss` and `.data`, but still not find out the logic. – Van Tr Jan 02 '20 at 18:15
  • 1
    I can't reproduce this. For which architecture with which compiler version and flags did you compile? – Armali Jan 07 '20 at 07:58

2 Answers2

1

The .bss has the size of the uninitialized global variables. These will be initialized to zero upon loading of the program.

If you initialize a global variable to something other than zero, it will no longer be in the .bss but will be in the .data segment. The data segment contains all initialized global variables (with their initial value).

Hence, the size of the .bss decreases and the size if the .data increases.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
0

It may be because of initialization of bss by reserving the basic 8 bytes, introducing all zeros so the memory manager does not read rubbish, but when we finally créate a variable that fits in 4 bytes, the bss is reduced (to occupy the less possible memory).

Román
  • 136
  • 1
  • 9