C/C++中const char *变量的内存布局位置

来源:互联网 发布:js 设置select 选中值 编辑:程序博客网 时间:2024/05/17 06:52

        const char *是一个比较特殊的指针类型,在函数中通过该类型定义的字符串变量存储在全局内存区,

而不是作为临时栈变量存储。可以通过下面的代码进行验证。

/* * ===================================================================================== * *       Filename:  test.cpp * *    Description:   * *        Version:  1.0 *        Created:  2013年06月14日 11时30分46秒 *       Revision:  none *       Compiler:  gcc * *         Author:  YOUR NAME (),  *   Organization:   * * ===================================================================================== */#include <cstdlib>#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>using namespace std;const char * GetLocalChar();int main(){cout<<GetLocalChar()<<endl;return  0;}const char * GetLocalChar(){printf("GetLocalChar start address = %p\n ",&GetLocalChar);const char * cpLocal="luoxiongwei";printf("cpLocal address = %p\n ",cpLocal);int n=0;printf("n address = %p\n ",&n);return cpLocal;}


 

 

 

    执行结果如下:


     从执行结果可见GetLocalChar起始地址0x8048749位于代码段,在低地址。

cpLocal const char *起始地址0x80488e2,位于初始化的全局变量段,相比GetLocalChar地址

稍高。而n这个变量的地址是0xbfae8258,位于高地址,程序栈区。

    从结果可以看出,const char * 的变量确实位于全局变量区。