I wanted to understand how a "C" program runs and store the data in machine. So I looked into Memory Layout of C from here and I followed the same instructions in my machine which is 64-bit.
First when I wrote the program (main
has only return 0;
) and used the size
command for the executable file: it showed a lot of difference in both text and data segments.
text data bss dec hex filename
10648 2400 2640 15688 3d48 33.exe
But in the website mentioned above it showed:
text data bss dec hex filename
960 248 8 1216 4c0 memory-layout
First Question:
What are the factors (hardware/software) that are responsible for the memory allocation?.
And what does dec
in the layout refer to? /Question ends here
But first I ignored this and started declaring the variables (global and static) to see where they are being stored. And I was facing a problem in this phase.
for this code:
#include <stdio.h>
int global;
int main(void) {
//static int x;
return 0;
}
I got output as:
text data bss dec hex filename
10648 2400 2656 15704 3d48 33.exe
That is because I declared (uninitialised) a global variable and that is why 16 bytes (int-64bit) of memory block has been added to the bss
so it became 2656 from 2640 (first example) I understand this.
Q2: But when I add the static int x
it is not adding the memory block to bss
anymore. Is this expected?
text data bss dec hex filename
10648 2400 2656 15704 3d48 33.exe
Q3: And finally when I initialize the global variable with 20
, data
got incremented (expected) and dec
also got incremented why?
text data bss dec hex filename
10648 2416 2656 15720 3d48 33.exe
I know I asked many questions here, but I wanted to know exactly how this memory management works in C.
Arigato:)
What are the factors (Hardware/Software) that are responsible for the memory allocation?. And what does dec in the layout refer to
Your program is divided into many sections when it runs. stack
contains the local variables. bss data
contains the uninitalized global variables. initialized data
contains the initialized global variables. text
contains your text (code).
dec
is the sum of text
, bss
, data
But when i add the static int x it is not adding the memory block to bss anymore.is it expected?
Keep it uninitialized then it will add.
Before adding static variable:
text data bss dec hex filename
1099 544 8 1651 673 a.out
After adding static variable:
text data bss dec hex filename
1099 544 16 1659 67b a.out
And finally when i initialize the global variable with 20, data got incremented (expected) and dec also got incremented. Why?
Because dec
is the sum of text
, data
, bss