I'm doing some tests here on my machine, and I realized that when I do not initialize a variable, its value tends to be 0, but it is only initialized with 0, when the code is compiled to 64 bits, after some tests , I verified that it seems to be the loader of the binary that fills the memory address with value 0, not the compiler. I would like to confirm if it is actually loader that puts the value 0, grateful
#include <stdio.h>
int x; //section .bss
int main(void) {
printf("%d\n", x);
return 0;
}
I'm doing some tests here on my machine, and I realized that when I do not initialize a variable, its value tends to be 0,
If a variable with static storage duration (such as your x
) is defined without an initializer, then its initial value is 0 (arithmetic types) or a null pointer (pointer types), or else it is an aggregate type and its members are initialized per these rules (recursively) or it is a union type and its first member is initialized per these rules. This is specified by paragraph 6.7.9/10 of the language standard, so in a conforming conforming implementation "tends to be" is too weak.
But note that this does not apply to automatic variables (those declared at block scope and without a storage class specifier). If an automatic variable is declared without an initializer then its initial value is indeterminate, and if you use such an object's value without first setting it then the behavior is undefined. Perhaps this is why you hedged.
but it is only initialized with 0, when the code is compiled to 64 bits,
If we're talking about conforming implementations, then the target architecture's word size has nothing to do with it.
after some tests , I verified that it seems to be the loader of the binary that fills the memory address with value 0, not the compiler.
That's implementation dependent. C does not specify. However, you tagged ELF, and C implementations that target ELF generally assign default-initialized objects to the BSS section, which is pretty much designed for the purpose. BSS takes up no space on disk but when loaded it is initialized to all-bits-zero.
I would like to confirm if it is actually loader that puts the value 0, grateful
The program loader, whatever form that takes in any given implementation, sets the initial value of every variable with static duration, regardless of whether it is defined with an initializer. It may do that by loading the value from disk or, in some cases, by zero-filling it without loading a specific value from disk, or possibly by some other mechanism. As already described, for variables assigned to the BSS section of an ELF object, the loader (dynamic linker in this case) zero-fills the representation.