Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top