- 1、内存分区模型
- 2、程序运行前
- 2.1 代码区
- 2.2 全局区
- 3、程序运行后
- 3.1 栈区
- 3.2 堆区
- 4、new操作符
C++程序在执行时,将内存大方向划分为4个区域:
1、代码区:存放函数体的二进制代码,由操作系统进行管理的
2、全局区:存放全局变量和静态变量以及常量
3、由编译器自动分配释放,存放函数的参数值,局部变量等
4、堆区:由程序员分配和释放,若程序员不释放,程序结束时由操作系统回收
内存四区的意义:
不同区域存放的数据,赋予不同的生命周期,给我们更大的灵活编程
2.1 代码区 2.2 全局区在程序编译后,生成了exe可执行程序,未执行该程序前分为2个区域,
全局变量:只要没写在函数中的变量都是全局变量;
#includeusing namespace std; #include //使用string字符 //全局变量 int g_a = 10; int g_b = 10; //const修饰全局变量,即全局常量 const int c_g_a = 10; const int c_g_b = 10; int main() { //全局区 //全局变量 cout << "全局变量g_a的地址:" << (int)&g_a << endl; cout << "全局变量g_b的地址:" << (int)&g_b << endl; //静态变量,在普通变量前面加上static,属于静态变量 static int s_a = 10; static int s_b = 10; cout << "静态变量s_a的地址:" << (int)&s_a << endl; cout << "静态变量s_b的地址:" << (int)&s_b << endl; //常量,包括字符串常量 cout << "字符串常量的地址为:" << (int)&"Hello World" << endl; //const修饰的变量,包括const修饰全局变量和局部变量 cout << "全局常量c_g_a的地址为:" << (int)&c_g_a << endl; cout << "全局常量c_g_b的地址为:" << (int)&c_g_b << endl; const int c_l_a = 10; const int c_l_b = 10; cout << "局部常量c_l_a的地址为:" << (int)&c_l_a << endl; cout << "局部常量c_l_b的地址为:" << (int)&c_l_b << endl; //创建普通局部变量 int a = 10; int b = 10; cout << "局部变量a的地址:" << (int)&a << endl; cout << "局部变量b的地址:" << (int)&b << endl; system("pause"); return 0; }
输出:
全局变量g_a的地址:6144052 全局变量g_b的地址:6144056 静态变量s_a的地址:6144060 静态变量s_b的地址:6144064 字符串常量的地址为:6135384 全局常量c_g_a的地址为:6134808 全局常量c_g_b的地址为:6134812 局部常量c_l_a的地址为:15990396 局部常量c_l_b的地址为:15990384 局部变量a的地址:15990372 局部变量b的地址:15990360 请按任意键继续. . .
总结:
栈区:由编译器自动分配释放,存放函数的参数值,局部变量等
注意事项:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放
#includeusing namespace std; #include //使用string字符 //栈区数据注意事项:不要返回局部变量的地址 //栈区的数据由编译器管理开辟和释放 int* func(int b)//形参数据也存放在栈区 { b = 10; int a = 10;//局部变量存放在栈区,栈区的数据在函数执行完后自动释放 return &a;//返回局部变量的地址 } int main() { //接收func函数的返回值 int* p = func(20); cout << *p << endl; cout << *p << endl; system("pause"); return 0; }
输出:
10 15601724 请按任意键继续. . .3.2 堆区
由程序员分配释放,若程序员不释放,程序结束时由操作系统回收
在c++中主要利用new在堆区开辟内存
#includeusing namespace std; #include //使用string字符 int* func() { //利用new关键字,将数据开辟到堆区 //指针本质也是局部变量,放在栈上,指针保存的数据是放在堆区 int* p=new int(10); return p; } int main() { //在堆区开辟数据 int* p = func(); cout << *p << endl; cout << *p << endl; cout << *p << endl; system("pause"); return 0; }
输出:
10 10 10 请按任意键继续. . .
解释图:
#includeusing namespace std; #include //使用string字符 //1、new的基本语法 int* func() { //在堆区创建整型的数据 //new返回的是该数据类型的指针 int *p=new int(10); return p; } void test() { int* a = func(); cout << *a << endl; cout << *a << endl; cout << *a << endl; //堆区的数据由程序员开辟、释放 //如果想释放,利用关键字delete //delete a; cout << *a << endl;//内存已经被释放,再次访问就是非法操作,会报错 } //2、在堆区利用new开辟数组 void test02() { //在堆区利用new创建10个整型的数组 int* array = new int[10];//10代表数组有10给元素 for (int i = 0; i < 10; i++) { array[i] =i+ 100; } for (int i = 0; i < 10; i++) { cout << array[i] << endl; } //释放堆区数组 //释放数组的生活,要加[] delete[] array; } int main() { // test(); test02(); system("pause"); return 0; }



