您的位置:首页 > 运维架构 > Linux

Linux下C/C++程序内存布局 各种类型数据存储区域及生长方向

2010-06-25 15:08 603 查看
在32位系统下,对于一个进程来说,理论上它具有4G的内存空间,那么写一小段代码来看看各个部分在逻辑上是如何分布的。
#include <stdio.h>
#include <stdlib.h>
int g_i = 3;
static int s_i = 4;
const int c_i = 5;
char* g_p = "abc";
void fun()
{}
static void s_fun()
{}
int main(int argc, char* argv[])
{
const int c = 6;
char* str = "abc";
int l_i = 3;
int *p_i = new int;
int *pp_i = (int*) malloc(sizeof(int));
int arr[10];
printf("%0x : global int i/n", &g_i);
printf("%0x : static int i/n", &s_i);
printf("%0x : global const int/n", &c_i);
printf("%0x : global char pointer/n", &g_p);
printf("%0x : global char pointer point content/n", g_p);
printf("%0x : local const int/n", &c);
printf("%0x : local char pointer/n", &str);
printf("%0x : local char pointer point content/n", str);
printf("%0x : local int /n", &l_i);
printf("%0x : local int pointer/n", &p_i);
printf("%0x : local int pointer point address(new)/n", p_i);
printf("%0x : local int pointer point address(malloc)/n", pp_i);
printf("%0x : array start address/n", &arr[0]);
printf("%0x : array end address/n", &arr[9]);
printf("%0x : function address/n", fun);
printf("%0x : static function addresss/n", s_fun);
return 0;

}

$ ./test | sort
运行结果如下:
80484a4 : function address
80484aa : static function addresss//符号表区
8048710 : global char pointer point content
8048710 : local char pointer point content//‘abc'字符串常量存储区
80488e8 : global const int//常量全局变量
8049a6c : global int i
8049a70 : global char pointer//全局变量
8049a74 : static int i//静态变量
95e4008 : local int pointer point address(new)
95e4018 : local int pointer point address(malloc)//堆分配内存区
bfc586d8 : array start address
bfc586fc : array end address
bfc58700 : local int pointer
bfc58704 : local int
bfc58708 : local char pointer
bfc5870c : local const int//栈区

通过上面的程序可以很清晰的发现各种类型数据的分布位置,以及生长的方向。
1. 符号表按定义的顺序由低->高地址发展
2. 堆分配的方向是由低->高发展
3. 栈从大概3G开始由高->低发展

可以画一张简图看看

high address |-----------------------|
. | 1G for kernel |
. |-----------------------|
. | stack |
. |-----------------------|
. | | |
. | |
. | |
. | |
. | | |
. |-----------------------|
. | heap |
. |-----------------------|
. | static variable |
. |-----------------------|
. | global variable |
. |-----------------------|
. | global const variable |
. |-----------------------|
. | string |
. |-----------------------|
. | symbol table |
low address |-----------------------|

通过size,我们可以看到程序主要段的详细信息
$ size test
text data bss dec hex filename
1980 304 4 2288 8f0 test

同样,在栈中,数组高位先分配,低位后分配。 栈是有大小限制的,如果越界就会异常退出,同时栈的大小默认值可以通过这个命令来查询
$ ulimit -a
$ ulimit -s [num] //设置栈大小
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: