全局和静态变量为什么被初始化为默认值吗? [英] Why are global and static variables initialized to their default values?

查看:545
本文介绍了全局和静态变量为什么被初始化为默认值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C / C ++,为什么初始化为默认值的全局变量和静态变量?

为什么不只是垃圾值离开吗?有什么特别的
原因造成的?


解决方案

  1. 安全:离开单独的内存泄漏会从其他进程或内核信息


  2. 效率:值是没用的,直到初始化的东西,它是更有效的在展开循环块零它们。操作系统甚至可以零空闲列表页面,当系统处于空闲状态,而不是当一些客户或用户正在等待程序启动。


  3. 重复性:离开值单独会使程序行为不可重复,使得虫子真的很难找到


  4. :这是清洁,如果程序可以从0开始,而不必弄乱code使用默认初始化


也许有人会那么想知道为什么汽车存储类也开始为乱码。答案是双重的:


  1. 这不,的感觉。的第一栈帧(即,添加到堆栈每一个新的页面)不接受零值。在垃圾或未初始化值,在相同的堆栈层次后续实例看到的都是真的被你自己的程序的另一种方法实例离开了previous价值和它的库。


  2. 有可能是二次(或其他)的运行时的性能损失与初始化汽车(功能当地人)任何东西有关。函数可能不使用任何或所有大阵,就是说,在任何给定调用,它可以被调用的时间数以百万计。静态和全局变量的初始化,OTOH,只需要发生一次。


In C/C++, why are globals and static variables initialized to default values?

Why not leave it with just garbage values? Are there any special reasons for this?

解决方案

  1. Security: leaving memory alone would leak information from other processes or the kernel.

  2. Efficiency: the values are useless until initialized to something, and it's more efficient to zero them in a block with unrolled loops. The OS can even zero freelist pages when the system is otherwise idle, rather than when some client or user is waiting for the program to start.

  3. Reproducibility: leaving the values alone would make program behavior non-repeatable, making bugs really hard to find.

  4. Elegance: it's cleaner if programs can start from 0 without having to clutter the code with default initializers.

One might then wonder why the auto storage class does start as garbage. The answer is two-fold:

  1. It doesn't, in a sense. The very first stack frame (i.e., every new page added to the stack) does receive zero values. The "garbage", or "uninitialized" values that subsequent instances at the same stack level see are really the previous values left by other method instances of your own program and it's library.

  2. There might be a quadratic (or whatever) runtime performance penalty associated with initializing auto (function locals) to anything. A function might not use any or all of a large array, say, on any given call, and it could be invoked thousands or millions of times. The initialization of statics and globals, OTOH, only needs to happen once.

这篇关于全局和静态变量为什么被初始化为默认值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆