Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are global variables stored?

AFAIK, there're 2 types of global variables, initialized and unintialized. How are they stored? Are they both stored in the executable file? I can think of initialized global variables having their initial values stored in executable file. But what needs to be stored for the uninitialized ones?

My current understanding is like this:

Executable file is organized as several sections, such as .text, .data, and .bss. Code is stored in .text section, initialized global or static data is stored in .data section, and uninitialized global or static data is stored in .bss section.

Thanks for your time to view my questions.

Update 1 - 9:56 AM 11/3/2010

I found a good reference here:

Segments in Assembly Language Source - Building the text and data segments with .text, .data, and .bss directives

Update 2 - 10:09 AM 11/3/2010

@Michael

  1. I define a 100 bytes of un-initialized data area in my assembly code, this 100-bytes is not stored in my executable file because it is NOT initialized.

  2. Who will allocate the 100-byte uninitialized memory space in RAM? The program loader?

Suppose I got the following code:

int global[100];

void main(void)
{
   //...
}

The global[100] is not initialzed. How will the global[100] be recoded in my executable file? And who will allocate it at what time? What if it is initialized?

like image 953
smwikipedia Avatar asked Nov 03 '10 01:11

smwikipedia


1 Answers

Initialized variable values are stored in the .data segment of the executable. Uninitialized ones don't have to be stored. They end up in the .bss segment in RAM, but the size of the segment is zero in the executable file, just the required amount of memory is stored in the segment descriptor. The code in the .text section is accessing these via offsets into the segment. Runtime linker-loader patches these references to actual virtual addresses. See, for example, the Executable and Linkable Format, which is used on most Unix-like operating systems.

like image 50
Nikolai Fetissov Avatar answered Oct 01 '22 02:10

Nikolai Fetissov