程序在运行过程中变量的保存位置与生命周期

本例说明了一个程序在运行的时候,各种变量所保存的位置。因为位置不同,自然,变量的生命周期也各不相同。

代码示例:

 

#include <iostream>

using namespace std;

int nGNum1;

void showStackAddress()
{
    cout<<"address of showStackAddress() is:\t["<<(void*)&showStackAddress<<"]"<<endl;
    int nStackNum1 = 10;
    static int snNum2 = 10;

    //显示函数中的临时变量的地址,应该位于程序的栈里
    cout<<"the address of nStackNum1 is: \t["<<&nStackNum1<<"]. value is:\t["<<nStackNum1<<"]"<<endl;

    //显示函数内部的静态变量,该地址应该与全局变量在一起。整数型的静态变量被初始化为0
    cout<<"the address of snNum2 is: \t["<<&snNum2<<"]. value is:\t["<<snNum2<<"]"<<endl;
}

int main(int argc, char ** argv)
{
    //显示程序的代码段的地址
    cout<<"process ["<<argv[0]<<"] start @["<<(void*)&main<<"]"<<endl;

    char * pcToArgv0 = argv[0];
    int nNum1 = 10;
    int *pnNum1 = new int (10);
    static int snNum1;

    //显示函数中的临时变量的地址,应该位于程序的栈里
    cout<<"the address of nNum1 is: \t["<<&nNum1<<"]. value is:\t["<<nNum1<<"]"<<endl;

    //显示全局变量的地址。整数型的全局变量被初始化为0
    cout<<"the address of nGNum1 is: \t["<<&nGNum1<<"]. value is:\t["<<nGNum1<<"]"<<endl;

    //显示函数内部的静态变量,该地址应该与全局变量在一起。整数型的静态变量被初始化为0
    cout<<"the address of snNum1 is: \t["<<&snNum1<<"]. value is:\t["<<snNum1<<"]"<<endl;

    //显示程序中的一些数据的地址。
    cout<<"the address of argv[0] is: \tpcToArgv0 @ ["<<&pcToArgv0<<"] to ["<<(void*)pcToArgv0<<"]. value is:\t["<<pcToArgv0<<"]"<<endl;

    //显示函数中用new手工生成的变量的地址,应该位于程序的堆里
    cout<<"the address of heap is: \tpnNum1 @ ["<<&pnNum1<<"] to ["<<pnNum1<<"]. value is:\t["<<*pnNum1<<"]"<<endl;

    showStackAddress();

    delete pnNum1;

    return 0;
}

编译:
用eclipse 自己编译的,实际上使用这个命令:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o cpptest_main.o ..\cpptest_main.cpp
g++ -o cpptest.exe cpptest_main.o

以下是程序的处理结果:
process [D:\projects\eclipse\cpptest\Debug\cpptest.exe] start @[0x4017e1]
the address of nNum1 is:     [0x22fec8]. value is:    [10]
the address of nGNum1 is:     [0x407020]. value is:    [0]
the address of snNum1 is:     [0x407028]. value is:    [0]
the address of argv[0] is:     pcToArgv0 @ [0x22fecc] to [0x341f28]. value is:    [D:\projects\eclipse\cpptest\Debug\cpptest.exe]
the address of heap is:     pnNum1 @ [0x22fec4] to [0x341f60]. value is:    [10]
address of showStackAddress() is:    [0x4016b0]
the address of nStackNum1 is:     [0x22fe9c]. value is:    [10]
the address of snNum2 is:     [0x404000]. value is:    [10]

程序说明:
一个程序在运行过程中,代码保存在代码段,临时变量保存在栈里,用new等手工生产的数据保存在堆里,一些没有名字的变量,也保存在堆里,例如argv[0],程序的全局变量和静态(局部)变量保存全局数据区。
全局变量和静态局部变量在定义的时候如果没有初始化,系统会为其进行初始化,例如,整型会被设定成数字0。

posted @ 2014-11-19 18:16  聚沙成塔  阅读(576)  评论(0编辑  收藏  举报