Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory layout of a c program

Tags:

c

I am reading this article http://www.geeksforgeeks.org/memory-layout-of-c-program/, it said " Uninitialized variable stored in bss", "Initialized variable stored in Data segment"

My question is why we need to have 2 separate segments for variables? 1. BSS 2. Data segment?

Why not just put everything into 1 segment?

like image 712
n179911 Avatar asked Mar 19 '26 06:03

n179911


2 Answers

BSS takes up no space in the program image. It just indicates how large the BSS section is and the runtime will set that memory to zero.

The data section is filled with the initial values for the variables so it takes space in the program image file.

like image 113
Michael Burr Avatar answered Mar 21 '26 19:03

Michael Burr


To my knowledge, uninitialized variables (in .bss) are (or should be) zerod out when entering the program. Initialised variables (.data) get a specific value.

This means that in the executable of your program (stored on disk), the .data segment must be included byte per byte (since each variable has a potentially different value). The .bss however, must not be saved byte per byte. One must only know the size to reserve in memory when loading the executable. The program knows the offset of each variable in .bss

To zero out all the uninitialized variables, a few assembler instructions will do (for x86: rep stosw with some register settings for instance).

Conclusion: loading and initialisation time for .data is lot worse than for large .bss segments, since the .data must be loaded from disk, and .bss is only to be reserved on the fly with very few cpu instructions.

like image 22
Painted Black Avatar answered Mar 21 '26 20:03

Painted Black