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