a triggerring question

Programming, for all ages and all languages.
Post Reply
ykissd
Posts: 1
Joined: Tue Aug 12, 2008 5:56 am

a triggerring question

Post 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?
eddyb
Member
Member
Posts: 248
Joined: Fri Aug 01, 2008 7:52 am

Re: a triggerring question

Post by eddyb »

from some uncleaned garbage. if there was some data and nothing cleaned to be fillled with 0, there is garbage
User avatar
AJ
Member
Member
Posts: 2646
Joined: Sun Oct 22, 2006 7:01 am
Location: Devon, UK
Contact:

Re: a triggerring question

Post 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
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re: a triggerring question

Post 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.)
Every good solution is obvious once you've found it.
quok
Member
Member
Posts: 490
Joined: Wed Oct 18, 2006 10:43 pm
Location: Kansas City, KS, USA

Re: a triggerring question

Post 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. :)
Post Reply