Search code examples
cmemorystatic-variablesaddress-space

Where memory will be allocated to "Uninitialized Static variable" upon initialization?


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?


Solution

  • 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)