3

Uninitialized static variable are always allocated in BSS. While .bss section is static as memory is allocated at compile time. As per many books "only variables that are initialized to a nonzero value occupy space" in executable. After program is loaded into memory, uninitialized static variables are still .bss.

**What happens when a function initializes it? ** Will it get moved to some other area?

Rajesh Pal
  • 118
  • 1
  • 7
  • 1
    Consider carefully your paraphrase: "only variables that are initialized *to a nonzero value* occupy space" (emphasis added). What about variables initialized to zero? These can be used without further initialization, so your apparent interpretation that runtime initialization must change something about space allocation cannot stand. As others have pointed out, the claim you refer to is about the executable *file*, not about the running program's image in memory. – John Bollinger May 01 '15 at 15:42
  • "Uninitialized static variable are always allocated in BSS" is not always true – M.M May 03 '15 at 06:13

3 Answers3

2

the rest of the quote:

"In the executable file, only variables that are initialized to a nonzero value occupy space."

I.E. when the executable file is loaded into memory, the needed space is allocated

user3629249
  • 16,402
  • 1
  • 16
  • 17
2

Upon initialization, memory is allocated to "Uninitialized Static variable” and this is moved to .data section.

Code File:

int a,b,c;

int main()
{

a=1;
b=2;
c=3;

scanf("%d",a);
}

Execution:

 # size a.out   
 text      data     bss     dec     hex filename
 1318       284      16    1618     652 a.out

# size core.18521 
text      data      bss     dec     hex   filename
28672    180224       0  208896   33000   core.18521 (core file invoked as ./a.out)
Rajesh Pal
  • 118
  • 1
  • 7
1

.bss doesn't occupy space in executable file. When program is started .bss is allocated and filled with 0. All not initialised object are located there. So when you initialise that variables memory is allocated.

Dmitry Poroh
  • 3,705
  • 20
  • 34