C++基础7:动态内存管理

本文详细介绍了C语言和C++中的动态内存管理。在C语言中,讲解了栈、堆的概念,以及malloc和free的使用,强调了内存泄漏的问题。而在C++中,介绍了new和delete操作符,包括对象的初始化和数组的动态分配,并阐述了内存释放的注意事项。文章通过实例展示了内存申请和释放的过程,帮助理解两种语言中动态内存管理的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、C语言动态内存管理

1.程序内存

 2.内存申请

3.内存释放

4.内存泄漏(内存浪费)

 二、C++动态内存管理

1.操作符new

2.释放delete


一、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;//安全

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值