未初始化的变量如何获得垃圾值? [英] How does an uninitiliazed variable get a garbage value?
问题描述
当我们创建一个变量但没有初始化它时,就会为它分配一些称为垃圾值的(随机)数字.
When we create a variable and don't initialize it, then some (random) number called garbage value is assigned to it.
- 如何将此值分配给变量?
- 这背后的整体概念/机制是什么?
- 这是否只发生在 C 中?
推荐答案
垃圾值未分配,而是该值已经存在.当您分配一个变量时,您正在保留一块内存 - 在您覆盖它之前,该内存将包含之前存在的任何随机"信息.
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).
有些语言会自动用零填充新分配的变量 - 这需要时间.在像 C 这样的更多自己动手"的语言中,这种额外的行为是没有保证的(尽管在某些系统上,无论语言如何,都会清除内存,例如作为安全措施)
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)
这篇关于未初始化的变量如何获得垃圾值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!