Jain Rachit Kumar
Jain Rachit Kumar

Reputation: 4277

integer variable size in bss and data segment

I am using a test program for understanding C memory model on linux 6.3 with kernal version 2.6.32-279.el6.x86_64 .

First i have compile below code,

#include <stdio.h>
int main(void)
{
    static int i = 100; /* Initialized static variable stored in DS*/
    return 0;
}

on running size command , i got below ,

[root@rachitjain jan14]# size a.out
   text    data     bss     dec     hex filename
   1040     488      16    1544     608 a.out

then, after removing the intialization for static variable 'i' , my code becomes ,

include <stdio.h>
int main(void)
{
    static int i ;
    return 0;
}

On running size on after compiling above ,

[root@rachitjain jan14]# size a.out
   text    data     bss     dec     hex filename
   1040     484      24    1548     60c a.out

There is 8 byte increment in bss section but only 4 bytes are reduced in the data section. Why the size is integer in getting doubled while moving to bss segment ?

I have tested this character and float as well , observed the same behavioral.

Upvotes: 4

Views: 1795

Answers (1)

user184968
user184968

Reputation:

Look, the answer is that the .bss section has a requirement to be aligned on 64 bits and the .data does not have this requirement.

How can you see this? When you build your program ld uses a default linker script in order to build your program. You can see it if you add -Wl,-verbose:

g++ main.cpp -Wl,-verbose

When you build 64 bit applicaton this is a default aligment for .bss section:

  .bss            :
  {
   *(.dynbss)
   *(.bss .bss.* .gnu.linkonce.b.*)
   *(COMMON)
   /* Align here to ensure that the .bss section occupies space up to
      _end.  Align after .bss to ensure correct alignment even if the
      .bss section disappears because there are no input sections.
      FIXME: Why do we need it? When there is no .bss section, we don't
      pad the .data section.  */
   . = ALIGN(. != 0 ? 64 / 8 : 1);
  }

As you can see ALIGN(. != 0 ? 64 / 8 : 1); tells to align to 8 bytes

When you build 32 bit applicaton (g++ -m32 main.cpp -Wl,-verbose) this is a default aligment for .bss section:

  .bss            :
  {
   *(.dynbss)
   *(.bss .bss.* .gnu.linkonce.b.*)
   *(COMMON)
   /* Align here to ensure that the .bss section occupies space up to
      _end.  Align after .bss to ensure correct alignment even if the
      .bss section disappears because there are no input sections.
      FIXME: Why do we need it? When there is no .bss section, we don't
      pad the .data section.  */
   . = ALIGN(. != 0 ? 32 / 8 : 1);
  }

Your .data section obviously does not have any ALIGN commands in the default linker script:

  .data           :
  {
    *(.data .data.* .gnu.linkonce.d.*)
    SORT(CONSTRUCTORS)
  }

Useful links:

Upvotes: 5

Related Questions