As we have seen so much theory in the PART-1 now let us see a real-time example to understand about these segments. we will use size(1) command to list various section sizes in a C code.
A simple C program is given below
#include <stdio.h> int main() { return 0; } $ gcc test.c $ size a.out text data bss dec hex filename 836 260 8 1104 450 a.outNow add a global variable as shown below
#include <stdio.h> int global; /* Uninitialized variable stored in bss*/ int main() { return 0; } $ gcc test.c $ size a.out text data bss dec hex filename 836 260 12 1108 454 a.outAs you can see BSS is incremented by 4 bytes.
Let us include a static variable as shown below.
#include <stdio.h> int global; /* Uninitialized variable stored in bss*/ int main() { static int i; /* Uninitialized static variable stored in bss */ return 0; } $ gcc test.c $ size a.out text data bss dec hex filename 836 260 16 1112 458 a.outAs you can see BSS is incremented by 4 bytes.
Now let us initialize the static variable so that it is saved in the initialized data segment.
#include <stdio.h> int global; /* Uninitialized variable stored in bss*/ int main() { static int i=10; /* Initialized static variable stored in DS*/ return 0; } $ gcc test.c $ size a.out text data bss dec hex filename 836 264 12 1112 458 a.outNow you can see that data section is incremented by 4 bytes and BSS is decremented by 4 bytes.
Let us even initialize the Global variable which makes it part of Data Segment.
#include <stdio.h> int global=10; /* Initialized variable stored in DS*/ int main() { static int i=10; /* Initialized static variable stored in DS*/ return 0; } $ gcc test.c $ size a.out text data bss dec hex filename 836 268 8 1112 458 a.outWe can see that data section is incremented by 4 bytes and BSS is decremented by 4 bytes.
Let us see what happens when we add a const variable.
#include <stdio.h> const int i = 1; int global=10; int main() { static int i=10; return 0; } $ gcc test.c $ size a.out text data bss dec hex filename 840 268 8 1116 45c a.outNow we can see that TEXT segment is incremented by 4 bytes.
References:
1. Narendra Kangralkar
No comments :
Post a Comment
Your comments are moderated