C++程序在执行时,将内存大方向划分为4个区域:
代码区:存放函数体的二进制代码,由操作系统进行管理的
全局区:存放全局变量和静态变量以及常量
栈区:由编译器自动分配释放, 存放函数的参数值,局部变量等
堆区:由程序员分配和释放,若程序员不释放,程序结束时由操作系统回收
内存四区意义:不同区域存放的数据,赋予不同的生命周期, 给我们更大的灵活编程空间
1.程序运行前
在程序编译后,生成了exe可执行程序,未执行该程序前分为两个区域
代码区:
(1)存放 CPU 执行的机器指令
(2)代码区是共享的,共享的目的是对于频繁被执行的程序,只需要在内存中有一份代码即可
?(3)代码区是只读的,使其只读的原因是防止程序意外地修改了它的指令
?全局区:
(1)全局变量和静态变量存放在此.
(2)全局区还包含了常量区, 字符串常量和其他常量也存放在此.
?(3)该区域的数据在程序结束后由操作系统释放
代码示例:
1 #include<iostream> 2 using namespace std; 3 //全局变量 4 int g_a = 10; 5 int g_b = 10; 6 7 //全局常量 8 const int c_g_a = 10; 9 const int c_g_b = 10; 10 11 int main() 12 { 13 //局部变量 14 int a = 10; 15 int b = 10; 16 17 //打印地址 18 cout << "局部变量a地址为: " << (int)&a << endl; 19 cout << "局部变量b地址为: " << (int)&b << endl; 20 21 cout << "全局变量g_a地址为: " << (int)&g_a << endl; 22 cout << "全局变量g_b地址为: " << (int)&g_b << endl; 23 24 //静态变量 25 static int s_a = 10; 26 static int s_b = 10; 27 28 cout << "静态变量s_a地址为: " << (int)&s_a << endl; 29 cout << "静态变量s_b地址为: " << (int)&s_b << endl; 30 31 cout << "字符串常量地址为: " << (int)&"hello world" << endl; 32 cout << "字符串常量地址为: " << (int)&"hello world1" << endl; 33 34 cout << "全局常量c_g_a地址为: " << (int)&c_g_a << endl; 35 cout << "全局常量c_g_b地址为: " << (int)&c_g_b << endl; 36 37 const int c_l_a = 10; 38 const int c_l_b = 10; 39 cout << "局部常量c_l_a地址为: " << (int)&c_l_a << endl; 40 cout << "局部常量c_l_b地址为: " << (int)&c_l_b << endl; 41 42 system("pause"); 43 44 return 0; 45 }
运行结果:
总结:
C++中在程序运行前分为全局区和代码区
代码区特点是共享和只读
全局区中存放全局变量、静态变量、常量
常量区中存放 const修饰的全局常量 和 字符串常量
2.程序运行后
栈区:
由编译器自动分配释放, 存放函数的参数值,局部变量等
?注意事项:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放
代码示例:
1 #include<iostream> 2 using namespace std; 3 int * func() 4 { 5 int a = 10; 6 return &a; 7 } 8 9 int main() 10 { 11 12 int *p = func(); 13 14 cout << *p << endl; 15 cout << *p << endl; 16 17 system("pause"); 18 19 return 0; 20 }
堆区:
由程序员分配释放,若程序员不释放,程序结束时由操作系统回收
?在C++中主要利用new在堆区开辟内存
代码示例:
1 #include<iostream> 2 using namespace std; 3 int* func() 4 { 5 int* a = new int(10); 6 return a; 7 } 8 9 int main() 10 { 11 12 int *p = func(); 13 14 cout << *p << endl; 15 cout << *p << endl; 16 17 system("pause"); 18 19 return 0; 20 }
总结:
堆区数据由程序员管理开辟和释放
堆区数据利用new关键字进行开辟内存(C语言中用malloc() 函数,在C++中尽量不要使用)
原文:https://www.cnblogs.com/guanrongda-KaguraSakura/p/13338807.html