Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

user process memory mapping — is the bss section always the same size?

Tags:

c

linux

This may be an older query but I could not find any satisfactory answer so far. To check the memory map of a file I wrote a small hello program.

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

int main(void)
{
        printf("Hello\n");
        return 0;
}

Now after compilation, when I use command size on its object file I get:

# size hello
   text    data     bss     dec     hex filename
   1133     492      16    1641     669 hello

I checked the size for other files too. I always get bss as 16. Is bss fixed? Is this included in data or it is out of it. I mean is this 16 is included in 492 or not. As far as I understand, bss is uninitialized data segment.

like image 608
iSegFault Avatar asked Dec 12 '22 09:12

iSegFault


1 Answers

The size of the BSS section varies between programs. It describes the amount of data that is initialized with 'all bytes zero'. The zeroes are not actually stored in the object file, but the size of the BSS section is stored.

The data section contains the initial values of all data structures that are not initialized to 'all bytes zero'; it too varies between programs. It does not include the space included in the BSS section.


You'd get a bigger BSS section with a program like this:

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

enum { A_SIZE = 100 };
static int a[A_SIZE];

int main(void)
{
    srand(time(0));
    for (int i = 0; i < A_SIZE; i++)
        a[i] = i;
    for (int i = A_SIZE; i > 0; i--)
    {
        int j = rand() % i;  // Not good random number generation!
        int t = a[j];
        a[j] = a[i-1];
        a[i-1] = t;
    }
    for (int i = 0; i < A_SIZE; i++)
        printf("%d\n", a[i]);
    return 0;
}

The code shuffles the numbers from 0 to 99, with some bias in the random number generation (so it isn't a perfect shuffle, but that really isn't the point of the exercise — it is just non-trivial code that uses a static array, even though a local variable would be sufficient). When I run size (on Ubuntu 13.10), I get:

text       data     bss     dec     hex filename
1593        584     432    2609     a31 shuffle

For comparison, on the 'hello' program in the question, I get:

text       data     bss     dec     hex filename
1200        560       8    1768     6e8 hello

The main difference is that the array a occupies 400 bytes; the other 24 bytes of BSS belong to other code.

like image 142
Jonathan Leffler Avatar answered Feb 06 '23 10:02

Jonathan Leffler