Akash Sinha
Akash Sinha

Reputation: 33

Does gcc initializes auto variable to 0?

Why am i getting 0. I is an auto variable, so it should print some garbage value, right? I am using gcc compiler.

#include "stdio.h"
void main() {
int i;
printf("%d\n", i);
}

Upvotes: 1

Views: 644

Answers (4)

haccks
haccks

Reputation: 106122

Does gcc initializes auto variable to 0?

Yes and No!
Actually uninitialized auto variables get indeterminate value (either an unspecified value or a trap representation1).

Using such variables in a program invoke undefined behavior-- behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which ANSI C International Standard imposes no requirements. (C11:§3.4.3)

Once UB is invoked you may get either expected or unexpected result. Result may vary run to run of that program, compiler to compiler or even version to version of same compiler, even on temperature of your system!


1. An automatic variable can be initialized to a trap representation without causing undefined behavior, but the value of the variable cannot be used until a proper value is stored in it. (C11: 6.2.6 Representations of types--Footnote 50)

Upvotes: 5

Brian Knoblauch
Brian Knoblauch

Reputation: 21409

It has become standard security practice for freshly allocated memory to be cleared (usually to 0) before being handed over by the OS. Don't want to be handing over memory that may have contained a password or private key! So, there's no guarantee what you'll get since the compiler is not guaranteeing to initialize it either, but in modern days it will typically be a value that's consistent across a particular OS at least.

Upvotes: 0

omerfarukdogan
omerfarukdogan

Reputation: 869

No, I get random values with gcc (Debian 4.9.2-10) 4.9.2.

ofd@ofd-pc:~$ gcc '/home/ofd/Destkop/test.c' 
ofd@ofd-pc:~$ '/home/ofd/Desktop/a.out' 
-1218415715
ofd@ofd-pc:~$ '/home/ofd/Desktop/a.out' 
-1218653283
ofd@ofd-pc:~$ '/home/ofd/Desktop/a.out' 
-1218845795

Upvotes: 1

Prabhu
Prabhu

Reputation: 3541

Variables declared inside a function are uninitialized. One cannot predict what might show up if you print them out. in your example main is a function too. Hence it so happens that it is zero.

When you declare variable to be static or gloabally, the compiler will have them initialzed to zero.

Upvotes: 0

Related Questions