Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why .bss size decrease when adding an initialized static variable?

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 ?

like image 201
Trevor Avatar asked Jun 26 '26 13:06

Trevor


1 Answers

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.

like image 169
Paul Ogilvie Avatar answered Jun 28 '26 05:06

Paul Ogilvie