简体   繁体   中英

Uninitialized local variable in C

I am learning C and found a similar question on a website. http://www.careercup.com/question?id=5707884834848768

I tried to understand it by writing my own program

int main()
{
   int i;
   printf("%d\n", i);
   int *ptr = &i;
   int**ptr2= &(ptr);
   return 0;
}

When the two pointer assignments are commented out, the output of this program is a random garbage value each time it is executed. If I uncomment the first pointer assignment, the output is always a fixed value (134513705). If I uncomment the second pointer assignment, the output is always 0.

I tried to understand it by using size command for a.out

text data bss dec
1141 252 8 1405
1157 256 8 1421
1157 256 8 1421

So, even though data values are same in 2nd and 3rd cases, the output is different. Why is the output having different values in the three cases?

As you can tell from the comments the expected output of this program is undefined. The reason for this is that the variable i was never initialized. Commenting out or adding back the pointer declarations is a bit of a red herring. Your printf statement renders the memory that 'i' is using in whatever state it is found. Running this on ideone.com outputs 0 regardless of what lines I comment in or out. Likely this is because they clear the memory before code execution. You could probably even change the output with different compiler options. The takeaway is that an uninitialized variable is a view on uninitialized memory and doesn't have a defined value.

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