linux应用进程内存空间

每个linux进程在被创建的时候,都被分配给一段内存空间,即系统给该进程分配一定的逻辑地址空间(VM),通常32位CPU的寻址空间是2^32=4G,所以理论来说一个进程的最大逻辑地址空间为4G,其中有1G是内核代码段。而另外一部分则分为代码段和数据段,数据段又可分为data\bbs\stack\heap等。具体的分配情况如下图所示:

在编译阶段可以确定的是text\data\bss段的大小。

如下的测试代码可以清晰看出变量和常量的内存分配位置:

 1 #include <iostream>
 2 using namespace std;
 3 //未初始化全局变量,bss段
 4 int g_uninit;
 5 //初始化的全局变量,data段
 6 int g_init = 100;
 7 int main(int argc, char* argv[])
 8 {
 9     //初始化静态变量,data段
10     static int s_init = 100;
11     //未初始化静态变量,bss段
12     static int s_uninit;
13     //局部变量,栈中
14     int l_temp = 0;
15     //局部变量,栈中
16     int l_temp1;
17 
18     //变量p本身存在栈中,p指向代码段的一个地址
19     char *p = "Test Mem";
20     
21     //动态分配,堆中
22     char *n_p = new char[20];
23     
24 
25     //main入口地址,代码段
26     cout << (int*)main << endl;
27     //p所指向地址,即"Test Mem"存放位置,代码段
28     cout << (int*)p << endl;
29     //p存放位置,栈中
30     cout << &p << endl;
31 
32     cout << &g_uninit << endl;
33     cout << &g_init << endl;
34     cout << &s_uninit << endl;
35     cout << &s_init << endl;
36     cout << &l_temp << endl;
37     cout << &l_temp1 << endl;
38 
39     return 0;
40 }

输出结果:

注:全局const常量通常是以立即数的形式在编译时直接加入到指令中,而局部const常量则是存放在函数栈中。验证程序:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 const int g_c=100;
 5 int g_init = 100;
 6 int g_uninit;
 7 int test();
 8 int main(int argc, char* argv[])
 9 {
10     const int l_c = 20;
11     cout << &l_c << endl;
12     cout << (int*)main << endl;
13     cout << &g_init << endl;
14     cout << &g_uninit << endl;
15     cout << &g_c << endl;
16     cout << (int*)test << endl;
17     return 0;
18 }
19 int test()
20 {
21     return 0;
22 }

编译执行,输出:

P.S 可以使用命令size来查看编译时可确定的内存段大小:

原文地址:https://www.cnblogs.com/litterrondo/p/3078386.html