文章目录
- 1.1 程序运行前
- 1.2 程序运行后
- 1.3 new 操作符
C++ 程序在执行时,将内存大致划分为 4个区域:
- 代码区:存放函数体的二进制代码,由操作系统进行管理;
- 全局区:存放全局变量和静态变量以及常量;
- 栈区:由编译器自动分配释放, 存放函数的参数值,局部变量等;
- 堆区:由程序员分配和释放,若程序员不释放,程序结束时由操作系统回收。
内存四区意义: 不同区域存放不同的数据,赋予不同的生命周期, 给我们更大的灵活编程。
1.1 程序运行前
在程序编译后,生成了 .exe
可执行程序,未执行该程序前分为两个区域:
(1)代码区: 存放 CPU 执行的机器指令
-
共享,对于频繁被执行的程序,只需要在内存中有一份代码即可;
-
只读,防止程序意外地修改了它的指令。
(2)全局区: 全局变量和静态变量存放在此,在程序结束后由操作系统释放
// Global variable
int g_a = 10;
int g_b = 10;
// Global constant
const int c_g_a = 10;
const int c_g_b = 10;
int main(){
// Local variable
int a = 10;
int b = 10;
// Static vaiiable
static int c_a = 10;
static int c_b = 10;
cout << "Local variable => a: " << (long)&a << endl;
cout << "Local variable => b: " << (long)&b << endl << endl;
cout << "Global variable => g_a: " << (long)&g_a << endl;
cout << "Global variable => g_b: " << (long)&g_b << endl << endl;
cout << "Static variable => c_a: " << (long)&g_a << endl;
cout << "Static variable => c_b: " << (long)&g_b << endl << endl;
// String constant
cout << "String constant => str:" << (long)&"Hello" << endl << endl;
cout << "Global constant => c_g_a: " << (long)&c_g_a << endl;
cout << "Global constant => c_g_a: " << (long)&c_g_b << endl << endl;
// Local constant
const int c_l_a = 10;
const int c_l_b = 10;
cout << "Local constant => c_l_a: " << (long)&c_l_a << endl;
cout << "Local constant => c_l_a: " << (long)&c_l_b << endl << endl;
return 0;
}
Local variable => a: 140737488345656
Local variable => b: 140737488345660
Global variable => g_a: 93824992247824
Global variable => g_b: 93824992247828
Static variable => c_a: 93824992247824
Static variable => c_b: 93824992247828
String constant => str:93824992239796
Global constant => c_g_a: 93824992239620
Global constant => c_g_a: 93824992239624
Local constant => c_l_a: 140737488345664
Local constant => c_l_a: 140737488345668
1.2 程序运行后
(1)栈区: 由编译器自动分配释放, 存放函数的参数值(形参),局部变量等。
注意事项:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放。
int *func(){
int a = 10;
return &a;
}
int main(){
int *p = func();
cout << *p << endl;
cout << *p << endl;
return 0;
}
使用 g++ main.cpp -o main
编译时,报出如下错误:
main.cpp: In function ‘int* func()’:
main.cpp:7:12: warning: address of local variable ‘a’ returned [-Wreturn-local-addr]
7 | return &a;
| ^~
main.cpp:6:9: note: declared here
6 | int a = 10;
| ^
(2)堆区: 由程序员分配释放,若程序员不释放,程序结束时由操作系统回收。
在 C++ 中,其主要利用
new
在堆区中开辟内存。
int *func(){
int *a = new int(10);
return a;
}
int main(){
int *p = func();
cout << func() << endl;
cout << *p << endl;
return 0;
}
0x55555556aed0
10
1.3 new 操作符
C++ 中利用 new
操作符在堆区开辟数据,由程序员手动开辟、手动释放,释放时可利用操作符 delete
。
示例1:基本语法
int *func(){
int *a = new int(10);
return a;
}
int main(){
int *p = func();
cout << func() << endl;
cout << *p << endl;
delete p;
// cout << *p << endl; // 为什么还是输出了?不应该报错吗?
return 0;
}
示例1:开辟数组
int main(){
int *arr = new int[10];
for (int i = 0; i < 10; i++){
arr[i] = i + 100;
}
for (int j = 0; j < 10; j++){
cout << arr[j] << '\t';
}
delete[] arr;
return 0;
}
100 101 102 103 104 105 106 107 108 109