简体   繁体   中英

Why local variable is initialized to zero

According to my knowledge, local variables are uninitialized ie, it contains garbage value. But following program is giving 0 (zero) as output.

main()
{
    int i;
    printf("%d\n",i);
}

When i run above program it is giving always 0. I know that 0 is also can be a garbage value but every time i am getting zero as output. Can anybody know reason for it?

Garbage value means whatever happened to be in that memory location. In your case, the value happened to be zero. It may not be the case in another machine.

Note that some compiler will fill uninitialized variable with some magic value for the purpose of debugging (like 0xA5A5 ), but it's usually not zero, either.

When i run above program it is giving always 0. I know that 0 is also can be a garbage value but every time i am getting zero as output.

Whatever happened to cause a 0 to be written into the location where i is now probably happens every time the program runs. Computers are nice and reliable like that. "garbage" doesn't necessarily mean "random" or "always changing," it just means "not meaningful in any context that I care about."

I think it is just an accident. local variable is indeed uninitialized, but the memory your compiler allocate for the (int i) variable is not used previously by your current process, so there is no garbage value.

Luck! The behaviour is undefined, and so the answer depends on your compiler and system. This time, you happened to get lucky that the first four bytes in that area of memory were zero. But there is no guarantee that it will always do so, from one system to the next or even from one invocation to the next.

A possible reason for printing always 0 is that main is started in a well defined state; more exactly, an ELF program is starting with a well defined stack (defined by the ELF specification) and registers, so its _start function (from crt*.o ) which is the ELF executable starting point gets a well defined stack, and calls main .

Try making your function some other name, and call it in various states (eg call it several times from main in more complex ways). Try also running your program with different program arguments and environments. You'll probably observe different values for i

Your program exhibits some undefined behavior (and with all warnings enabled gcc -Wall is warning you).

As far as I know, uninitialized variables in Linux are first "allocated" in the Zero Page - a special page that contains only zeros.
Then, at the first write to the unitialized variable, the variable is moved from the zero page to another page that is not write-protected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM