Global variable's life time is until the completion of the program. But what is the point of having two sections for global variables based on initialized and uninitialized. The point is to reduce the executable size of the program before going to discuss about the BSS section we need to understand what process structure, and how the structure looks in the memory (RAM) at the time of execution.
If we are not initialized the global variables the loader will take care to initialize all global variables to zero (0). The loader is designed in such a way to initialize the global to zero while loading the process into RAM. If we are keeping initialized and uninitialized variable in the same block loader will initialize to zero for all the initialized variables too. Compiler developer decided to divide the global sectioninto two parts
1. DATA
2. .BSS
All initialized variable will go to DATA section, this will be decided in compilation time itself. But uninitialized variable will go into BSS section. This block will be created at the time of loading so it reduces the executable size of the program.
#include<stdio.h>
int a[10000000]={1};
main()
{
long i;
for(i=0;i<10000000;i++)
printf("%d",a[i]);
}
//save it as ubss.c
>gcc -o ubss ubss.c
>ls -l ubss
output:-rwxr-xr-x 1 vishal vishal 40007193 2012-03-02 19:50 ubss
Program Memory Layout |
If we are not initialized the global variables the loader will take care to initialize all global variables to zero (0). The loader is designed in such a way to initialize the global to zero while loading the process into RAM. If we are keeping initialized and uninitialized variable in the same block loader will initialize to zero for all the initialized variables too. Compiler developer decided to divide the global sectioninto two parts
1. DATA
2. .BSS
All initialized variable will go to DATA section, this will be decided in compilation time itself. But uninitialized variable will go into BSS section. This block will be created at the time of loading so it reduces the executable size of the program.
Now lets try out some example to proof how bss is effective save memory....
#include<stdio.h>
int a[10000000];
main()
{
long i;
for(i=0;i<10000000;i++)
printf("%d",a[i]);
}
//save it as bss.c
compile above program
>gcc -o bss bss.c
>ls -l bss
output:
-rwxr-xr-x 1 vishal vishal 7149 2012-03-02 19:44 bss
so size of this executable is 7149= around 7KB
#include<stdio.h>
int a[10000000]={1};
main()
{
long i;
for(i=0;i<10000000;i++)
printf("%d",a[i]);
}
//save it as ubss.c
>gcc -o ubss ubss.c
>ls -l ubss
output:-rwxr-xr-x 1 vishal vishal 40007193 2012-03-02 19:50 ubss
size of this executable is :40MB
because here a[] is initialized and memory is already allotted to it...
No comments:
Post a Comment