C/C++内存管理_cpp

目录

1. C/C++内存分布

2. C语言中动态内存管理方式:malloc/calloc/realloc/free

3. C++内存管理方式

3.1 new/delete操作内置类型 

3.2 new和delete操作自定义类型

4. operator new与operator delete函数

4.1 operator new与operator delete函数(重点)

5. new和delete的实现原理

5.1 内置类型

5.2 自定义类型  


1. C/C++内存分布

我们先来看下面的一段代码和相关问题

int globalVar = 1;
static int staticGlobalVar = 1;
void Test()
{
static int staticVar = 1;
int localVar = 1;
int num1[10] = { 1, 2, 3, 4 };
char char2[] = "abcd";
const char* pChar3 = "abcd";
int* ptr1 = (int*)malloc(sizeof(int) * 4);
int* ptr2 = (int*)calloc(4, sizeof(int));
int* ptr3 = (int*)realloc(ptr2, sizeof(int) * 4);
free(ptr1);
free(ptr3);
}
1. 选择题:
选项: A.栈 B.堆 C.数据段(静态区) D.代码段(常量区)
globalVar在哪里?____
staticGlobalVar在哪里?____
staticVar在哪里?____
localVar在哪里?____
num1 在哪里?____
char2在哪里?____
*char2在哪里?___
pChar3在哪里?____
*pChar3在哪里?____
ptr1在哪里?____
*ptr1在哪里?____

【说明】
1. 又叫堆栈 -- 非静态局部变量 / 函数参数 / 返回值等等,栈是向下增长的。
2. 内存映射段 是高效的 I/O 映射方式,用于装载一个共享的动态内存库。用户可使用系统接口

 创建共享共享内存,做进程间通信。(Linux课程如果没学到这块,现在只需要了解一下

3. 用于程序运行时动态内存分配,堆是可以上增长的。

4. 数据段--存储全局数据和静态数据。

5. 代码段 -- 可执行的代码 / 只读常量

2. C语言中动态内存管理方式:malloc/calloc/realloc/free

见这篇帖子,就不重复介绍了。动态内存管理-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/2301_79409088/article/details/137975736?spm=1001.2014.3001.5501

3. C++内存管理方式

      C语言内存管理方式在C++中可以继续使用,但有些地方就无能为力,而且使用起来比较麻

烦,因此C++又提出了自己的内存管理方式:通过new和delete操作符进行动态内存管理

3.1 new/delete操作内置类型 

int main()
{
 
    int* p1 = new int;      // 动态申请一个int类型的空间
    int* p2 = new int[10];  // 动态申请10个int类型的空间
	int* p4 = new int[5]{1,2,3,4,5};// 动态申请5个空间,数组初始化为{1,2,3,4,5}
	int* p3 = new int(10);  // 动态申请一个int类型的空间并初始化为10
	
	delete p1;
	delete[] p2;
	delete p3;

	// new/delete 和 malloc/free最大区别是
    // new/delete 对于【自定义类型】除了开空间还会调用构造函数和析构函数

}
注意:申请和释放单个元素的空间,使用 new delete 操作符,申请和释放连续的空间,使用
new[] delete[] ,注意:匹配起来使用。

3.2 newdelete操作自定义类型

class A
{
public:
A(int a = 0)
: _a(a)
{
cout << "A():" << this << endl;
}
~A()
{
cout << "~A():" << this << endl;
}
private:
int _a;
};
int main()
{
// new/delete 和 malloc/free最大区别是 new/delete对于【自定义类型】除了开空间
还会调用构造函数和析构函数
A* p1 = (A*)malloc(sizeof(A));
A* p2 = new A(1);
free(p1);
delete p2;
// 内置类型是几乎是一样的
int* p3 = (int*)malloc(sizeof(int)); // C
int* p4 = new int;
free(p3);
delete p4;
A* p5 = (A*)malloc(sizeof(A)*10);
A* p6 = new A[10];
free(p5);
delete[] p6;
return 0;
}

 注意:在申请自定义类型的空间时,new会调用构造函数,delete会调用析构函数,而malloc

free 不会

4. operator newoperator delete函数

4.1 operator newoperator delete函数(重点)

       new和delete是用户进行动态内存申请和释放的操作符operator new 和operator delete
系统提供的全局函数new在底层调用operator new全局函数来申请空间,delete在底层通过
operator delete全局函数来释放空间
/*
operator new:该函数实际通过malloc来申请空间,当malloc申请空间成功时直接返回;申请空间
失败,尝试执行空 间不足应对措施,如果改应对措施用户设置了,则继续申请,否
则抛异常。
*/
void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
{
// try to allocate size bytes
void *p;
while ((p = malloc(size)) == 0)
if (_callnewh(size) == 0)
{
// report no memory
// 如果申请内存失败了,这里会抛出bad_alloc 类型异常
static const std::bad_alloc nomem;
_RAISE(nomem);
}
return (p);
}
/*
operator delete: 该函数最终是通过free来释放空间的
*/
void operator delete(void *pUserData)
{
_CrtMemBlockHeader * pHead;
RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));
if (pUserData == NULL)
return;
_mlock(_HEAP_LOCK); /* block other threads */
__TRY
/* get a pointer to memory block header */
pHead = pHdr(pUserData);
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
_free_dbg( pUserData, pHead->nBlockUse );
__FINALLY
_munlock(_HEAP_LOCK); /* release other threads */
__END_TRY_FINALLY
return;
}
        通过上述两个全局函数的实现知道,operator new 实际也是通过malloc来申请空间,如果
malloc申请空间成功就直接返回,否则执行用户提供的空间不足应对措施,如果用户提供该措施
就继续申请,否则就抛异常。operator delete 最终是通过free来释放空间的

5. newdelete的实现原理

5.1 内置类型

        如果申请的是内置类型的空间, new malloc delete free 基本类似,不同的地方是:
new/delete 申请和释放的是单个元素的空间, new[] delete[] 申请的是连续空间,而且 new
申请空间失败时会抛异常,malloc 会返回 NULL

5.2 自定义类型  

new 的原理
1. 调用 operator new 函数申请空间
2. 在申请的空间上执行构造函数,完成对象的构造
delete 的原理
1. 在空间上执行析构函数,完成对象中资源的清理工作
2. 调用 operator delete 函数释放对象的空间
new T[N] 的原理
1. 调用 operator new[] 函数,在 operator new[] 中实际调用 operator new 函数完成 N 个对
象空间的申请
2. 在申请的空间上执行 N 次构造函数
delete[] 的原理
1. 在释放的对象空间上执行 N 次析构函数,完成 N 个对象中资源的清理
2. 调用 operator delete[] 释放空间,实际在 operator delete[] 中调用 operator delete 来释
放空间
#0 Homer::RtpSessionState::deprovisionAtDestruction (this=0x7f1fe00e7650) at ../components/mos/state/session_state/src/rtp_session_state.cpp:886 886 ../components/mos/state/session_state/src/rtp_session_state.cpp: No such file or directory. [Current thread is 1 (Thread 0x7f1ffffff700 (LWP 372))] (gdb) bt #0 Homer::RtpSessionState::deprovisionAtDestruction (this=0x7f1fe00e7650) at ../components/mos/state/session_state/src/rtp_session_state.cpp:886 #1 0x00005653759a8e33 in Homer::DeviceState::~DeviceState (this=0x7f1fe00ecf50) at ../components/mos/state/device_state/src/device_state.cpp:87 #2 0x0000565375c4229e in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release (this=0x7f1fe00ecf40) at /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/shared_ptr_base.h:155 #3 std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count (this=0x7f1fe00bbb08) at /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/shared_ptr_base.h:730 #4 std::__shared_ptr<Homer::DeviceStateBase, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr (this=0x7f1fe00bbb00) at /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/shared_ptr_base.h:1169 #5 Homer::Device::~Device (this=0x7f1fe00bb070) at ../components/mos/device/src/device.cpp:94 #6 0x0000565375c3c08a in Homer::WebsocketDevice::~WebsocketDevice (this=0x7f1fe00bb070) at ../components/mos/device/src/websocket_device.h:31 #7 Homer::WebsocketClientDevice::~WebsocketClientDevice (this=0x7f1fe00bb070) at ../components/mos/device/src/websocket_client_device.cpp:20
06-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

于本淡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值