r/C_Programming • u/Altruistic-Tie1943 • Jul 25 '26
Discussion why default value of global and local variables are different?
why in c language the default value of global variables is set to be 0 but the default value of local variables is garbage value?
57
Upvotes
80
u/EpochVanquisher Jul 25 '26
I think, historically, because the cost of initializing global variables is cheap (you only have to do it once).
For local variables, you would have set the value to zero many times.
31
u/thegreatunclean Jul 25 '26
Global variables that aren't explicitly initialized are all placed in a section in memory generally called the "BSS". When your program is loaded it is trivial for the OS to zero the entire block out very quickly with a single bulk
memset. A cheap action done once and a design choice that simplifies the binary format by combining zero-initialized and uninitialized blocks into a single entity.Local variables live on the stack and constantly pop into and out of existence as the program executes. Zeroing them every time would mean every single function would need extra chunks of setup and teardown code to make it all happen. A bunch of extra work at every level of the program that will most likely be immediately thrown out when the variable is inevitably initialized to something else.
8
u/Traveling-Techie Jul 25 '26
I always initialize variables. Makes me nervous otherwise.
5
u/SmokeMuch7356 Jul 25 '26
Technically, all variables with
staticstorage duration are initialized to 0, global or not:globhasstaticstorage duration by virtue of being declared at file scope,statis explicitly declaredstatic. Both will be initialized to 0 when the program is loaded. Ifstatis set to a different value at runtime, it will retain that value between calls tofoo.locwill not be initialized; its value will be whatever bit pattern happens to be at that location when it's created each timefoois called.As others have said, initializing things on program load is a cheap operation; it doesn't affect runtime performance.
11
u/Axman6 Jul 25 '26
Local variables are allocated on the stack, so their default value is whatever is in that portion of memory at the time the stack reaches it. Programs don’t clear the stack when function return, so if the stack was ever larger than it is now, function local variables will just be pointing to data from previous function calls (and random function).
Global variables are allocated in several different sections of memory depending on their declaration, see this for more info
https://stackoverflow.com/questions/64626917/global-variables-and-the-data-section
4
u/sciencekm Jul 25 '26
Global variables are initialized at load time. So it is 'free' for the app (not free for the loader) and is done once.
Local variables can be initialized or not initialized depending on whether it is static or on stack. Being on stack, having to initialize it on each call is inefficient. The developer can decide when and what values the stack variables should get.
In the following illustration, the local variable 'initflag', being static, is initialized to 0, once. After it gets modified, succeeding calls to the function will not re-initialize the variable. It will get whatever value it was last changed to.
void init(void) {static int initflag;if (initflag == 0) {initflag = 1;initmem();}}3
u/[deleted] Jul 25 '26
Local -> stack -> whatever happens to be there
Global bss initialised to 0 on startup
2
u/Pleasant-Form-1093 Jul 25 '26
You can have local variables zero initialised if you want, use -ftrivial-auto-var-init=0 (for clang and gcc, I don't use msvc so I don't know how it works over there).
There will be a small performance penalty associated with it because every time a method is called, the entire allocated stack frame has to be zeroed
2
u/Bitter-Ad-9431 Jul 25 '26
global variables are an actual address in your data segment, usually in the BSS or BSSZ section. So the linker can initialize that variable at link time.
Local variables are either in registers or some offset above the stack pointer. The stack and register contents are unpredictable, and most compilers do not generate code to initialize them every time on function entrance. Some compilers initialize local variables if you select some major debugging option.
2
u/uptotwentycharacters Jul 25 '26
It's ultimately because each global variable has a fixed address in the program, so the OS can set them during process creation. Even if the variables in question end up being written to before being read from, initializing them is cheap since it only has to be done once and programs aren't supposed to have many global variables in the first place.
Local variables are generally stored on the stack or in registers, so they would have to be initialized each time the function is called. So it only initializes local variables if you explicitly tell it to, otherwise it expects that you will assign to the variable before reading from it. Furthermore, it's easier for the programmer to detect uninitialized-read-before-write errors with local variables, since they only have to look at that function body (and a variable being left unassigned after the first few executable statements is often a red flag). Such errors are harder to find with globals, since the code responsible for assigning to them could be anywhere in the program.
2
u/BadRuiner Jul 25 '26
learn asm bro /s
The global value is a reference to the offset from the beginning DLL or EXE. If there is no value, then it will be zero. Compiler will not fill it with random bullshit each fckn compilation time.
A local value is a reference to an offset from the stack (google it plz). The stack grows when a new function is called and shrinks when the function exits. It takes a FUCKING LOT of computational operations to reset it every time, so it stays the same. If you want a default value of 0, do it yourself, u a dev, u do u want do.
2
u/pskocik Jul 25 '26 edited Jul 25 '26
Zero-initializing globals is FREE on a hosted platform (a secure OS will have zero-initialized memory before giving it to user space (the loader)) and can be made very cheap elsewhere. (Zero-initialized globals are typically all lumped together into a single section (array). This section (typically named .bss) need not take up size in the program image and memsetting the whole thing to zero upon loading can be accelerated via SIMD unlike zeroing individiual tiny variables.)
Zero initializing stack variables would slow things down and add extra code to functions. This code would need to run every time the variable's scope is entered, which would become costly especially for larger variables (on-stack buffers).
Pedantically, zero initialization or no initialization for uninitialized variables isn't really for globals vs locals. It's for static-lifetime variables vs others (register and auto class). Local variable in C are zero initialized too IFF they're uninitialized STATICS. Zero initializing of type remaineders (after initializing some members of the type) applies to auto (on-stack) locals too, despite the potential costs. But you don't have to pay those costs because you can leave the variable uninitialized and just assign to the fields that you want initialized.
1
u/flatfinger Jul 28 '26
An important thing to note about automatic-duration objects is that they may be capable of holding values outside their type's range, and the Standard waives jurisdiction over what might happen as a result. Consider e.g.
A C implementation targeting the 32-bit ARM may use a 32-bit register to hold
q, ensuring that any time code modifies that register the upper bits are written as zero. As it happens, the most convenient register to use for holdingqwould be the register that will receivex, and will need to hold the return value when the function exits. If code never does anything with that register except whenqis modified, and the function is invoked with mode equal to zero, the effect would be that the function would return whatever was passed inx, even if that happened to be greater than 65535.C99 added rules that made explicit the Standard's waiver of jurisdiction over such cases; even though the rationale cited had to do with some obscure architectures, quirks like the above which can arise even with straightforwardly generating code for commonplace ones. Modern compiler optimizations can amplify the effect of such quirks, e.g. by omitting a check a programmer had included in code which calls
test()to ensure that result would only be used if it was less than 65536, at the same time as generates code fortest()that might return values beyond that range.1
u/TiredEngineer-_- Jul 25 '26
https://en.cppreference.com/cpp/language/initialization
See Static Initialization, 'in practice'.
https://en.wikipedia.org/wiki/.bss
""" despite filling bss with zero is not required by the C standard, all variables in .bss are required to be individually initialized to some sort of zeroes according to Section 6.7.8 of C ISO Standard 9899:1999 or section 6.7.9 for newer standards """
""" Peter van der Linden, a C programmer and author, says, "Some people like to remember it as 'Better Save Space'. Since the BSS segment only holds variables that don't have any value yet, it doesn't actually need to store the image of these variables. The size that BSS will require at runtime is recorded in the object file, but BSS (unlike the data segment) doesn't take up any actual space in the object file." """
Depending on the type of global: const, static, thread_local, etc. It can end up in different segments: .ro, .data, .bss, etc.
However, these are "preliminary" to your program running. They MUST be initialized before your program enters main, which is once (cheap). However, when your program loads, it may be in different parts of memory between runs. So your memory for the stack / heap are "dirty" from other processes there before the OS gave you the memory pages to work with.
The distinguishing difference you can see here:
https://stackoverflow.com/questions/17159666/where-are-global-variables-located-in-the-elf-file#17159828
Is that explicitly initialized vars end up in .data, while others are in .bss, const initialized globals end up in .ro, and typically your process is prevented write access to this segment.
These standards mandate 0 init for .bss because as others mentioned, security, history, etc happened and people agreed "0 is good" to initialize it to. 0 is a number available in all size types, number bases, etc. So its logically sound and safe, faster, and easier to use it for initialization instead of say, 1. (Find size of each type, compute offset, go set to 1, repeat).
The alternative would be something like "the OS will be required to fetch pages of memory equal to or greater than the size of the .bss segment, then zero them out. And, this is a simple task that hardware / OS just do. (Think calloc, memset, etc, those C abstractions are doing sys level work thats available). However, zeroed pages are scarce compared to dirty pages. This defers the "initializing" to the program, and the stack is fast enough that performance payoff of
int x; and int x = 0;
Is not really observable, even with 100 variables (linearly, not in a loop like an array, which introduces branching and program counter manipulation).
0
u/bothunter Jul 25 '26
Officially, neither are initialized and both will contain garbage. But modern operating systems put processes in their own memory space which is cleared out before it starts. This will clear out your globals. However, your local variables are on the stack and while that stack will start out with all zeros when the process starts, it won't stay that way for very long.
0
u/TwystedLyfe Jul 25 '26
https://github.com/openbsd/src/blob/af7d239111f95af790f7f9f164aa1f9479ff6e5f/lib/libc/crypt/arc4random.c#L95
Look hard at line 95.
There are times when you need garbage.
-1
u/GenericFoodService Jul 25 '26
Because the C standard says nothing about it, so the specific implementations of C compilers decide what the behavior here should be. If you want the value initialized, you would have initialized it. Why add additional logic to the compiler and compiled binaries that doesn't solve a real-world problem?
0
u/Glum_Preference_2936 Jul 25 '26
If you declare a global array variable of several megabytes, like
static int buf[1024*1024*32] = {0}. You could see that resulting application doesn't really have a size of 32MiB. (Unless you fill it explicitly with some nonzero values)However, using local variables, the stack pointer is incremented and whatever address it points to is your data, which could be data from previous operations or just garbage.
0
u/duane11583 Jul 25 '26
Global variables are easily Located next to each other and thus zeroed or intitalized
Local cars are often stored on the stack and thus the value in the location where they are stored is the value in that spot previously
Example the return address for a function call might be in that location Or maybe another variable from a function that has completed
0
u/neopunk2025 Jul 26 '26
I suggest you to always init your global variables too.
Under Windows, no problem, when you start, quit and start again your app, your global variables will be initialized even if you changed its value during the execution.
Under Android, it's a different story, because the way the OS is working.
-5
u/digitaljestin Jul 25 '26
I wouldn't count on those globals being initialized if I were you. That's not in any spec that I'm aware of. Just initialize your variables, and assume they are garbage until you do.