I'm learning about memory layout in C, I used the size
command on a file compiled using gcc from the following C code
#include <stdio.h>
int main(){
return 0;
}
Did the same but added an uninitialized int before the main function
int x;
int main ...
the output of the size
command is the same
I understand that uninitialized variables goes to bss section in memory, so it's supposed to give me a different bss size with the second code ( 8 4 = 12 bytes ) so why the results are the same?
and what is initially stored in the data and bss sections ( their initial size is respectively 512 and 8 bytes) ?
CodePudding user response:
C compilers generally optimise their code unless you tell them not to.
As a rule of thumb, any function or variable you create but don't subsequently reference will be optimised out. In this case, your int x;
was never subsequently referenced, so the compiler simply ignored it.
If, for example, you'd used return x;
as the final statement in your main()
function, that would then have referenced x
. The compiler would then be obliged to allocate space in .bss
for it, since you had not explicitly assigned a value and it was not declared static
*.
Bear in mind, though, that .bss
items are essentially virtual in nature. They've been declared but not instantiated. In other words, the accounting's been done, and at execute time space will finally be assigned in memory, but they won't occupy physical space in the executable.
One word of caution: the .bss
segment is commonly zeroed at execute time, but this is not guaranteed behaviour, and you should not rely upon it. In other words, your x
may vary!
(* If you had assigned a non-zero value, that would put it in the .data
segment. If you had assigned a zero value, or declared it static without an initialiser, it would be put in a segment that would be guaranteed zeroed at execute time, or in .data
.)