Uninitialized variable in C

c, initialization, undefined-behavior, variables

Solution

Reading the value of an uninitialized variable leads to undefined behavior. And undefined behavior means that it can crash. It doesn't mean it will or it is obliged to crash.

An uninitialized variable has unspecified value - it's just unknown what its value is. So in practice, with any sane implementation, this kind of code will presumably never crash. There's a valid memory address backing the variable, it has some garbage content, `printf()` reads it without problem, interprets it as an integer and prints it, that's all.

Problem

I'm a little bit confused. As far as I know, if you declare an int in C, without initializing it, for e.g: `int x;` so its value is indeterminate. So if we try to use it or should have undefined behavior. So if i'm running the following code in VS2010 It crash the program. ``` int main(){ int a; printf("%d\n",a); return 0; } ``` Now lets take a look at the next code, which does not provide any warning and does not crash (why?) ``` void foo(int *var_handle){ // do nothing } int main(){ int a; foo(&a); printf("%d\n",a); // works, prints some big value return 0; } ``` Can you explain the behavior of this? we only added a call to a function which does nothing at all, but now program wont crash.

Original source

Related problems