目录
一、C语言动态内存管理
1.程序内存
操作系统会在内存里给程序分配空间,用于程序运行
a)stack栈:临时变量,局部变量
b)heap堆:动态内存
int a = 0;
int b = 0;
int c = 0;
cout << &a << endl;
cout << &b << endl;
cout << &c << endl;
int * p1 = (int*) malloc (4);
int * p2 = (int*) malloc (4);
int * p3 = (int*) malloc (4);
cout << p1 << endl;
cout << p2 << endl;
cout << p3 << endl;
//abc地址越来越小,p123越来越大
arm64
0x16cf7b648//4个字节
0x16cf7b644
0x16cf7b640
0x145606790//16位对齐
0x1456067a0
0x1456067b0
2.内存申请
void* malloc( size_t size )// size_t size 字节数
int * p1 = (int*) malloc (4);
int * p1 = (int*) malloc (3);//一次申请16个字节
3.内存释放
void free( void* ptr ) ;//没有自动回收机制
4.内存泄漏(内存浪费)
p = (int *) malloc(4 * sizeof(int));
// ...
p = (int *) malloc(8 * sizeof(int));
// ...第一次的地址被第二次覆盖,第一次的地址消失了,无法找回,回收不了
free (p);
void foo()
{
int* p = (int *) malloc( sizeof(int));//p是函数的局部变量,函数return,p消失,作用域到此为止 ,无法回收
return;
} //memory leak
注意:在哪里申请就在哪里释放
二、C++动态内存管理
1.操作符new
//allocate an int, default initializer (do nothing)
int * p1 = new int; //int多大就申请多少,内存随机值
//allocate an int, initialized to 0
int * p2 = new int();初始化0
//allocate an int, initialized to 5
int * p3 = new int(5); 初始化5
//allocate an int, initialized to 0
int * p4 = new int{};//C++11
//allocate an int, initialized to 5
int * p5 = new int {5};//C++11
//allocate a Student object, default initializer
Student * ps1 = new Student;
//allocate a Student object, initialize the members
Student * ps2 = new Student {"Yu", 2020, 1}; //C++11
//allocate 16 int, default initializer (do nothing)
int * pa1 = new int[16];//16个int,64个字节
//allocate 16 int, zero initialized
int * pa2 = new int[16]();
//allocate 16 int, zero initialized
int * pa3 = new int[16]{}; //C++11
//allocate 16 int, the first 3 element are initialized to 1,2,3, the rest 0
int * pa4 = new int[16]{1,2,3}; //C++11初始化前3个,后面置零
//allocate memory for 16 Student objects, default initializer
Student * psa1 = new Student[16];
//allocate memory for 16 Student objects, the first two are explicitly initialized
Student * psa2 = new Student[16]{{"Li", 2000,1}, {"Yu", 2001,1}}; //C++11
2.释放delete
//deallocate memory
delete p1;
//deallocate memory
delete ps1;
//deallocate the memory of the array
delete pa1;
//deallocate the memory of the array
delete []pa2;//整数两者没区别
//deallocate the memory of the array, and call the destructor of the first element
delete psa1;
//deallocate the memory of the array, and call the destructors of all the elements
delete []psa2;//安全