C++内存管理
目录
1. C/C++内存分布
2. C++中动态内存管理
1.new/delete操作内置类型
2.new和delete操作自定义类型
3. operator new与operator delete函数
1 operator new与operator delete函数(重点)
4. new和delete的实现原理
1.内置类型
2.自定义类型
5. 定位new表达式(placement-new)
6. 常见面试题
1 malloc/free和new/delete的区别
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在哪里?__C__ staticGlobalVar在哪里?__C__staticVar在哪里?__C__ localVar在哪里?__A__num1 在哪里?__A__char2在哪里?__A__ *char2在哪里?_A__pChar3在哪里?__A__ *pChar3在哪里?__D__ptr1在哪里?__A__ *ptr1在哪里?__B__
2. C++中动态内存管理
1.new/delete操作内置类型
void Test()
{// 动态申请一个int类型的空间int* p1 = new int;// 动态申请一个int类型的空间并初始化为10int* p2= new int(10);// 动态申请10个int类型的空间int* ptr3 = new int[3];
//释放空间delete p1;delete p2;delete[] p3;
}
2.new和delete操作自定义类型
class A
{
public:A(int a = 0): _a(a){cout << "A():" << this << endl;}~A(){cout << "~A():" << this << endl;}
private:int _a;
};int main()
{A* p1 = (A*)malloc(sizeof(A)); //malloc失败返回NULLA* p2 = new A(1); //new失败抛异常int *p3=new int[10] {1,2,3,4};free(p1);delete p2;delete [] p3;return 0;
}
3. operator new与operator delete函数
1 operator new与operator delete函数(重点)
void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
{
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);
}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_FINALLYreturn;
}
/*
free的实现
*/
#define free(p) _free_dbg(p, _NORMAL_BLOCK)
4. new和delete的实现原理
1.内置类型
如果申请的是内置类型的空间,new和malloc,delete和free基本类似,不同的地方是:new/delete申请和释放的是单个元素的空间,new[]和delete[]申请的是连续空间,而且new在申请空间失败时会抛异常,malloc会返回NULL。
2.自定义类型
5. 定位new表达式(placement-new)
6. 常见面试题
1 malloc/free和new/delete的区别
2.内存泄漏
C/C++程序中一般我们关心两种方面的内存泄漏:
(1)堆内存泄漏(Heap leak)
堆内存指的是程序执行中依据须要分配通过malloc / calloc / realloc / new等从堆中分配的一 块内存,用完后必须通过调用相应的 free或者delete 删掉。假设程序的设计错误导致这部分内存没有被释放,那么以后这部分空间将无法再被使用,就会产生Heap Leak。
(2)系统资源泄漏