UNIX环境高级编程第153有这么一张图
为了更好的理解的这张图,可以写个测试程序,查看各种变量所位于进程的真实位置
#include<stdio.h>
#include<stdio.h>
#include<malloc.h>
int a = 1;
int b;
const int c = 1;
const int d;
static int e = 1;
static int f ;
int main()
{
int g ;
int h = 1;
int *i = (int*)malloc(sizeof(int));
int const j;
int const k = 1;
printf("a = global initial var is %p,a = %d\n",&a,a);
printf("b = global uninitial var is %p,b = %d\n",&b,b);
printf("c = global const initial var is %p,c = %d\n",&c,c);
printf("d = global const uninitial var is %p,d = %d\n",&d,d);
printf("e = global static initial var %p,e = %d\n",&e,e);
printf("f = global static uninitial var %p,f = %d\n",&f,f);
printf("g = local uninit var is %p,g= %d\n",&g,g);
printf("h = local init var is %p,h=%d\n",&h,h);
printf("i = dynamic pointer is %p\n",i);
printf("j = local const uninit var is %p,j= %d\n",&j,j);
printf("k = local init var is %p,k=%d\n",&k,k);
while(1)
{
}
return 0;
}
运行程序后
同时查看 cat/proc/2413/maps 2413指的是该进程的PID
由进程分布图和运行结果可以看出
a = global initial var is 0x804a018,a = 1 初始化数据段
b = global uninitial var is 0x804a038,b = 0 未初始化数据段
c = global const initial var is 0x8048690,c = 1 正文段
d = global const uninitial var is 0x804a034,d = 0 未初始化数据段
e = global static initial var 0x804a01c,e = 1 初始化数据段
f = global static uninitial var 0x804a02c,f = 0 未初始化数据段
g = local uninit var is 0xbfc6758c,g= 2655012 栈
h = local init var is 0xbfc67590,h=1 栈
i = dynamic pointer is 0x8d72008 堆
j = local const uninit var is 0xbfc67594,j= 1322069 栈
k = local init var is 0xbfc67598,k=1 栈
l = local uninitial static var is 0x804a030,k=0 未初始化数据段
m = local initial static var is 0x804a020,m=1 初始化数据段
总结:static都是位于数据存储区(初始化和未初始化段),局部变量都是位于栈。全局变量位于数据存储区。全局初始化const变量位于代码段,非初始化位于数据存储区。
指针分配的位于堆。
问题:从maps似乎看不出初始化数据段和未初始化数据段,这得再次查询资料确认一下。
引申:不能从函数返回局部变量指针,
自动分配的指针可以,加上static变量的指针也可以。