如何确定未初始化变量的值? [英] How are the values of uninitialized variables determined?

查看:178
本文介绍了如何确定未初始化变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个程序:

int main()
{

    short myVariableName1;  // stores from -32768 to +32767
    short int myVariableName2;  // stores from -32768 to +32767
    signed short myVariableName3;  // stores from -32768 to +32767
    signed short int myVariableName4;  // stores from -32768 to +32767
    unsigned short myVariableName5;  // stores from 0 to +65535
    unsigned short int myVariableName6;  // stores from 0 to +65535

    int myVariableName7;  // stores from -32768 to +32767
    signed int myVariableName8;  // stores from -32768 to +32767
    unsigned int myVariableName9;  // stores from 0 to +65535

    long     myVariableName10;  // stores from -2147483648 to +2147483647
    long     int myVariableName11;  // stores from -2147483648 to +2147483647
    signed   long myVariableName12;  // stores from -2147483648 to +2147483647
    signed   long int myVariableName13;  // stores from -2147483648 to +2147483647
    unsigned long myVariableName14;  // stores from 0 to +4294967295
    unsigned long int myVariableName15;  // stores from 0 to +4294967295
    cout << "Hello World!" << endl;
    cout << myVariableName1 << endl;
    cout << myVariableName2 << endl;
    cout << myVariableName3 << endl;
    cout << myVariableName4 << endl;
    cout << myVariableName5 << endl;
    cout << myVariableName6 << endl;
    cout << myVariableName7 << endl;
    cout << myVariableName8 << endl;
    cout << myVariableName9 << endl;
    cout << myVariableName10 << endl;
    cout << myVariableName11 << endl;
    cout << myVariableName12 << endl;
    cout << myVariableName13 << endl;
    cout << myVariableName14 << endl;
    cout << myVariableName15 << endl;
    cin.get();

    return 0;
}

打印出未分配的变量将打印以前存储在该内存位置中的任何内容.我注意到的是,在多个连续的执行过程中,打印的值没有改变-这告诉我每次执行时内存中的位置都是相同的.

Printing out the unassigned variables will print whatever was stored in that memory location previously. What I've noticed is that across multiple consecutive executions the printed values are not changing - which tells me that the locations in memory are the same each time they execute.

我很好奇这是如何确定的,为什么会这样.

I'm just curious as to how this is determined, why this is so.

推荐答案

这些变量位于堆栈中.程序的执行看起来是确定性的,因此,每次运行该程序时,都会发生相同的事情.它并不一定要选择相同的地址(如今,许多运行时都使用地址空间随机化技术来确保两次运行之间堆栈地址相同),但是堆栈上的相对地址包含相同的地址每次都是数据.

Those variables live on the stack. The execution of your program looks to be deterministic, so every time you run it the same things happen. It's not choosing the same address necessarily (many runtimes these days make use of Address Space Randomization techniques to ensure that the stack addresses are not the same between runs), but the relative addresses on the stack contain the same data every time.

这篇关于如何确定未初始化变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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