tags:

views:

549

answers:

4

Hi!

I struck a little problem when learning. I know that uninitialized global variables in C are assigned to the .bss section in the executable ELF file. But what happens to them when I start to use them? I.e. do they get a place on the heap or somewhere else?

I tried to find out by printing the address of the (still uninitialized) global variable with

printf("%x",&glbl);

which always return the same value 0x80495bc... Why?

+2  A: 

The global variables always get static memory, if they're uninitialized they don't have space in the binary, but they do get it in memory when the binary is loaded to the process memory space.

Arkaitz Jimenez
+1  A: 

The BSS is a placeholder defined in your executable (or ELF) format. So it does not take up disk space, but only specifies what memory region should be allocated by the linker or loader.

The exact operation depends on the operating system. Since you refer to ELF, I assume it is for use in an embedded system. If you build for ROMmable code, your linker cmd file will map the BSS to a static address region.

In case you build for an operating system (i.e. Linux), the loader from the operating system will perform a relocation pass, in which it maps all locations marked as relative in the excecutable format to physical or logical locations in memory.

Because you mention always seeing the same value, this indicates that the process is repeatable for your system. Expect to see changes when you change linker files (i.e. address regions), link order (i.e. modules will get assigned space in a different order) or operating system.

Wether or not you use the BSS values, the address will remain the same for the process you run.

Adriaan
+10  A: 

When the OS loads your program, it allocates enough storage from your program's address space to store everything in the .bss section and zeros all of that memory. When you assign or read from or take the address of the variable, you're manipulating that memory that was allocated to provide storage for the .bss section.

Nick Meyer
Ah and this also explains why the value contained by the uninitialized global variable was always zero. Thanks!
Patrick
Some compilers/architectures support a SBSS section for small data. This is often done as an optimisation so that the data can be fetched by indexing from the start of the SBSS section. This can often be done by using the gp register and 16-bit indexing
zebrabox
+1  A: 

That BSS section is given a memory block in the process address space just like the code and stack sections (and any other ELF may have). Once there, they don't go anywhere. The loader arranges things then calls the process entry point.

paxdiablo