uninitialized variables of a object file not showing in linux size command

305 views Asked by At

Created a source file test1.c with the following code :

#include<stdio.h>
#include<stdlib.h>

int x = 15;
int d = 15;
int m = 18;
int k = 0;
int c = 0;
int l;

int main()
{
    int y = 5;
    int ma = 10;
    int am = 10;
    printf("Hello World\n");
    return 0;
}

Compiled the following code with the command :

gcc -c test1.c

To check the size of the various segments of memory used the size command :

size test1.o

The output that I obtained :

   text    data     bss     dec     hex  filename
   114       12       8     134      86   test1.o

And I found that whenever I add a global uninitialized variable like int l in above the bss segment stays unchanged. The bss segment shows just those variables that are initialized to 0. But according to definition bss segment should contain uninitialized variables.

Also whenever I add a initialized global pointer like :

int *p = &x

it increases the size of the data segment by 12 rather than 8 ( which is the size of a integer pointer on my machine ).

What is wrong with my interpretation ?

1

There are 1 answers

1
Sourav Ghosh On

And I found that whenever I add a global uninitialized variable like int l in above the bss segment stays unchanged.

That's the expected behaviour. Quoting from wikipedia article, (emphasis mime)

[...] Since the BSS segment only holds variables that don't have any value yet, it doesn't actually need to store the image of these variables. The size that BSS will require at runtime is recorded in the object file, but BSS (unlike the data segment) doesn't take up any actual space in the object file.

So, it's unlikely that the size for bss will change, upon changing the number of uninitialized variables with static storage. You can refer to this earlier answer for more elaboration on the why part.