在空间中的内存分配如图所示
通过以下程序可以更加清晰的看出地址之间的联系:
#include <stdio.h>
int add(int a, int const e)
{
int c;
int d = 0;
static f = 1;
c = a + e;
printf("local(null) &c = %p\n", &c);
printf("local(eval) &d = %p\n", &d);
printf("const e = %p\n", &e);
printf("static &f = %p\n", &f);
return c;
}
int main(void)
{
int a = 3;
int b;
char str1[10] = {"hello"};
char str2[10];
printf("allover(eval) &a = %p\n", &a);
printf("allover(null) &b = %p\n", &b);
printf("array(eval) &str1 = %p\n", str1);
printf("array(null) &str2 = %p\n", str2);
b = add(3, 4);
return 0;
}
执行结果如下所示
allover(eval) &a = 0xbf803820
allover(null) &b = 0xbf80381c
array(eval) &str1 = 0xbf803812
array(null) &str2 = 0xbf803808
local(null) &c = 0xbf8037e4
local(eval) &d = 0xbf8037e0
const e = 0xbf8037f4
static &f = 0x8049714
由此可知全局变量里,不论是一般变量,还是数组,为定义的保存在bss段,而定义的保存在之后的.data段里。
局部变量就全部保存在栈空间,在数据堆之上。
static修饰的变量全部保存在.data段。
const修饰的在一定程度上属于只读常量,所以存在rodata段。