prev up next   top/contents search

comp.lang.c FAQ list · Question 3.10b

Q: People told me that if I evaluated an undefined expression, or accessed an uninitialized variable, I'd get a random, garbage value. But I tried it, and got zero. What's up with that?

A: It's hard to answer this question, because it's hard to see what the citation of the ``unexpected'' value of 0 is supposed to prove. C does guarantee that certain values will be initialized to 0 (see question 1.30), but for the rest (and certainly for the results of those undefined expressions), it is true that you might get garbage. The fact that you happened to get 0 one time does not mean you were wrong to have expected garbage, nor does it mean that you can depend on this happening next time (much less that you should write code which depends on it!).

Most memory blocks newly delivered by the operating system, and most as-yet-untouched stack frames, do tend to be zeroed, so the first time you access them, they may happen to contain 0, but after a program has run for a while, these regularities rapidly disappear. (And programs which unwittingly depend on a circumstantial initial value of an uninitialized variable can be very difficult to debug, because the ``expected'' values may coincidentally arise in all the small, easy test cases, while the unexpeccted values and the attendant crashes happen only in the larger, longer-running, much-harder-to-trace-through invocations.)

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North