Page 1 of 1

a triggerring question

Posted: Tue Aug 12, 2008 6:00 am
by ykissd
When you use a variable in programming and do not initialize it, it holds a garbage value.

Where do this garbage value comes from?

Re: a triggerring question

Posted: Tue Aug 12, 2008 6:07 am
by eddyb
from some uncleaned garbage. if there was some data and nothing cleaned to be fillled with 0, there is garbage

Re: a triggerring question

Posted: Tue Aug 12, 2008 6:50 am
by AJ
Hi,

Local (non-static) variables are generally held on the stack, so they contain previous stack values.

Global and static variables are generally held within the data section of your binary or on (if allocated dynamically) on the heap. This means that they contain either data that was stored at that location in the past, or the values that were randomly in the RAM when the DIMMs were powered up. None of these values should be relied on.

Cheers,
Adam

Re: a triggerring question

Posted: Tue Aug 12, 2008 7:37 am
by Solar
I'll try even shorter:

That garbage is either a) a random leftover from power-up, or b) a similarily random value left by some other application (or yourself).

(Yes, that means that security-sensitive applications should zero-out their data memory before releasing it.)

Re: a triggerring question

Posted: Tue Aug 12, 2008 8:51 am
by quok
Uninitialized variables are stored in .bss, which is supposed to be zero initialized when it is allocated for your program. Of course that only works the first time you use a variable, but you still shouldn't rely on it.

A little off topic, but with GCC, it's possible to get even zero initialized variables into your .bss section instead of .data, if you pass the -fconserve-space flag. Hmm, well that was the case way back in 2.95, I'm not sure if that flag actually still exists, or if it became default behavior or not. I'm assuming it did not, because it's still pretty standard practice to initialize a variable to 0 just to force it to be located in .data. This flag may be set when using -Os, but at this point I'm too lazy to double check. :)