0

I am trying to understand how memory allocation works for any C code which is executed or compiled.

I have written following 5 separate small codes which will help me understand the memory allocation process.

  1. segment_size1.c

    int main(){
        printf("hellow world");
        return 0;
    }
    
  2. segment_size2.c

    //Adding uninitialized static int variable This would increase the size of BSS by 4 bytes.
    int main()
    {
        static int mystatic;
        printf("Hellow world");
        return 0;
    }
    
  3. segment_size3.c

    // Adding initialized static int variable, this would increase the size of initialized data
    // segment by 4 bytes.
    
    int main()
    {
            static int mystatic;
            static int mystatic1 = 100;
            printf("Hellow world");
            return 0;
    }
    
  4. segment_size4.c

    // Adding un-initialized global int variable, this would increase the size of BSS segment by 4 bytes.
    
    int myglobal;
    int main()
    {
            static int mystatic;
            static int mystatic1 = 100;
            printf("Hellow world");
            return 0;
    }
    
  5. segment_size5.c

    // Adding initialized global int variable, this would increase the size of data segment by 4 bytes.
    
    int myglobal;
    int myglobal2 = 500;
    int main()
    {
        static int mystatic;
        static int mystatic1 = 100;
        printf("Hellow world");
        return 0;
    }
    

According to my understanding, if we compile above files then after compiling segment_size2.c BSS size should get incremented by 4 bytes and after compiling segment_size3.c Data size should get incremented by 4 bytes. But when I hit size command, I got following results,

    size segment_size1 segment_size2 segment_size3 segment_size4 segment_size5
       text    data     bss     dec     hex filename
       1217     560       8    1785     6f9 segment_size1
       1217     560       8    1785     6f9 segment_size2
       1217     564      12    1793     701 segment_size3
       1217     564      12    1793     701 segment_size4
       1217     568      16    1801     709 segment_size5

Here We can clearly see that bss and data segment is simultaneously getting updated after compiling segment_size3. How is this possible?

pratik
  • 1
  • 2

1 Answers1

0

We can clearly see that bss and data segment is simultaneously getting updated

This is the distinction between where the initial values != 0 are saved and where the static/global variables are

Before the main execution the initial values !=0 are copied into the global/static variables, the global/static variables having the initial value 0 are also set to 0 of course

bruno
  • 32,421
  • 7
  • 25
  • 37