How does an uninitiliazed variable get a garbage v

2019-01-02 21:04发布

When we create a variable and don't initialize it, then some (random) number called garbage value is assigned to it.

  • How this value is assigned to the variable?
  • What is whole concept/mechanism behind this?
  • Does this happen only in C?

5条回答
心情的温度
2楼-- · 2019-01-02 21:31

The garbage value is not assigned, rather the value is already there. When you allocate a variable you are reserving a piece of memory - until you overwrite it that memory will contain whatever "random" information was there before.

As a metaphor, think of allocating a variable like buying a piece of land - until you do something with it (like build a house) the land will just have whatever trash was already sitting there (like an old crumbling house).

Some languages will automatically fill newly allocated variables with zeros - this takes time to do. In more "do-it-yourself" languages like C this extra behavoir is not guarenteed (though on some systems memory is cleared regardless of language, for example as a security measure)

查看更多
临风纵饮
3楼-- · 2019-01-02 21:32

C standards say:

Implementation: detailed examination of an implementation at: https://stackoverflow.com/a/36725211/895245 Summary:

  • local: the address is never written to, so whatever was there previously gets used
  • global: .bss
查看更多
何处买醉
4楼-- · 2019-01-02 21:33

Memory is used and reused at various points in your application. For example, as the call stack of your application grows and shrinks the same location in memory may be overwritten many, many times. The thing to remember is that as a piece of memory is abandoned it is not zeroed out, so if you do not specify a new initial value for that place in memory when you use it again you will get the old, "garbage" value.

Some languages and structure implementations do default-initialize memory as it is used. Others do not, so it is important to read the documentation of your language carefully to know what to expect.

查看更多
泪湿衣
5楼-- · 2019-01-02 21:45

Nobody explicitly assigns a grabage value. If you create a variable, only location of the variable is determined, and not its value. Thats why we are initializing it. The garbage value might come from some previous operations over the same memory by old processes! So it can hold anything. I think it holds to pretty good number of languages. I am not sure about the list! :)

查看更多
皆成旧梦
6楼-- · 2019-01-02 21:49

When we create a variable and don't initialize it, then nothing happens. When you read value from that variable you get data from memory where variable located now. It could looks like garbage/random value only because variables are placed in memory with some degree of randomness.

查看更多
登录 后发表回答