The ambiguous behavior of a .bss segment in a C program

I wrote a simple C program (test.c) below: -

#include<stdio.h> int main() { return 0; } 

and performed the following procedure to understand resizing in the .bss segment.

 gcc test.c -o test size test 

The output came out as: -

  text data bss dec hex filename 1115 552 8 1675 68b test 

I did not declare anything globally or static. Therefore, please explain why the bss segment size is 8 bytes.

I made the following change: -

 #include<stdio.h> int x; //declared global variable int main() { return 0; } 

But, to my surprise, the result was the same as the previous one: -

  text data bss dec hex filename 1115 552 8 1675 68b test 

Please explain. Then I initialized global: -

 #include<stdio.h> int x=67; //initialized global variable int main() { return 0; } 

The data segment size increased as expected, but I did not expect the bss segment size to decrease to 4 (as opposed to 8 when nothing was announced). Please explain.

 text data bss dec hex filename 1115 556 4 1675 68b test 

I also tried the objdump and nm commands, but they also showed the x variable occupying .bss (in the second case). However, no changes to the bss size are displayed in the size command.

I followed the procedure as per: http://codingfox.com/10-7-memory-segments-code-data-bss/ where the outputs are going fine as expected.

+6
source share
2 answers

When compiling a simple main program, you also link the startup code. This code responds, among other things, to init bss.

This code is code that "uses" the 8 bytes you see in the .bss section.

You can break this code using the - nostartfiles gcc option:

-nostartfiles

Do not use standard system startup files when linking. Standard system libraries are commonly used unless -nostdlib or -nodefaultlibs are used.

To test use the following code

 #include<stdio.h> int _start() { return 0; } 

and compile it with

 gcc -nostartfiles test.c 

You will see that .bss is set to 0

  text data bss dec hex filename 206 224 0 430 1ae test 
+6
source

Your first two snippets are identical since you are not using the variable x .

try it

 #include<stdio.h> volatile int x; int main() { x = 1; return 0; } 

and you should see .bss resizing.

Please note that these 4/8 bytes are something inside the startup code. What it is and why it changes in size, it is impossible to tell without going into all the details of the mentioned startup code.

+1
source

Source: https://habr.com/ru/post/1012449/


All Articles