Chinna
Chinna

Reputation: 4002

Why local variable is initialized to zero

According to my knowledge, local variables are uninitialized i.e, 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?

Upvotes: 1

Views: 1368

Answers (6)

MrDor
MrDor

Reputation: 108

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.

Upvotes: 0

lulyon
lulyon

Reputation: 7265

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.

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122493

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.

Upvotes: 4

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 (e.g. 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).

Upvotes: 1

gavinb
gavinb

Reputation: 20048

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.

Upvotes: 1

Caleb
Caleb

Reputation: 125037

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."

Upvotes: 5

Related Questions