【C++自学笔记】C/C++内存管理

一、C/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";
	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、所在内存区域

globalVar->数据段(静态区)

staticGlobalVar->数据段(静态区)
staticVar->数据段(静态区) localVar->
num1->  
char2->栈(栈帧) *char2->栈(栈帧)
pChar3->栈(栈帧) *pChar3->代码段
ptr1->栈(栈帧) *ptr1->

2、sizeof 和 strlen 

sizeof(num1) = 40 sizeof(char2) = 5
sizeof(pChar3) = 4 / 8 sizeof(ptr1) = 4 / 8
strlen(char2) = 4 strlen(pChar3) = 4

3、C/C++中程序内存区域划分 

                                                            

栈:又叫堆栈,非静态局部变量/函数参数/返回值等等,栈是向下增长的;

内存映射段:是高效I/O映射方式,用于装载一个共享的动态内存库。用户可使用系统接口创建共享内存,做进程间通信;

堆:用于程序运行时动态内存的分配,堆是向上增长的;

数据段:存储全局数据和静态数据;

代码段:可执行的代码 / 只读常量;

二、C语言中动态内存管理方式

1、malloc / calloc / realloc 和 free

void Test() {
	int* ptr1 = (int*)malloc(sizeof(int));
	free(ptr1);
	int* ptr2 = (int*)calloc(4, sizeof(int));
	int* ptr3 = (int*)realloc(ptr2, sizeof(int) * 10);

	free(ptr3);
}

注意:ptr2不需要释放,因为 realloc 只是对 ptr2的原有基础上进行了扩容,实际上用的是同一块内存空间;

2、malloc / calloc / realloc 的区别

共同点:都是程序猿从堆上申请空间的方法,并且需要手动释放或者在程序结束运行的时候自动释放,否则会造成内存泄露;

malloc:分配的内存是位于堆中的,并且没有初始化内存的内容,因此基本上malloc之后,调用函数memset来初始化这部分的内存空间;

calloc:将初始化这部分的内存;

realloc:则对malloc 、 realloc 申请的内存进行大小的调整;

3、alloca

alloca是从上申请内存空间,且不需要释放,由系统自动释放;

三、C++内存管理方式

1、new / delete 操作内置类型

void Test() {
	int* ptr1 = new int;
	int* ptr2 = new int(10);
	int* ptr3 = new int[3];

	delete ptr1;
	delete ptr2;
	delete[] ptr3;
}

                                                       ptr1 ==> 动态申请了一个int类型的空间;

                                                       ptr2 ==> 动态申请了一个int类型的空间并初始化为10;

                                                       ptr3 ==> 动态申请了一个int型数组,数组大小是在[ ]中指定

注意:申请和释放单个元素的空间,使用 new 和 delete 操作符;申请和释放连续空间,使用 new[ ] 和 delete[ ];

2、new / delete 操作自定义类型

class TestT {
public:
	TestT()
		:_data(0)
	{
		cout << "TestT()" << endl;
	}
	~TestT() {
		cout << "~TestT()" << endl;
	}
private:
	int _data;
};

以 malloc 来动态申请内存:

void Test() {
	TestT* t1 = (TestT*)malloc(sizeof(TestT));
	free(t1);

	TestT* t2 = (TestT*)malloc(sizeof(TestT) * 10);
	free(t2);
}

以 new 来动态申请内存:

void Test() {
	TestT* t1 = new TestT;
	delete t1;

	TestT* t2 = new TestT[10];
	delete t2;
}

结论:在申请自定义类型的空间时,new 会调用构造函数,delete 会调用析构函数,而 malloc 和 free 不会;

四、operator new和operator delete函数

new 和 delete 是用户进行动态内存申请和释放的操作符,operator new 和 operator delete 是系统提供的全局函数;

new 在底层是调用operator new 全局函数来申请空间,delete 是在底层调用 operator delete 全局函数来释放空间;

void* __CRTDECL operator new(size_t size) _THROW(_STD bad_alloc){
	void* p;
	while((p = malloc(size) == 0)
		if (_callnewh(size) == 0) {
			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;
		/* 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;
}
/*
free的实现
*/
#define free(p) _free_dbg(p, _NORMAL_BLOCK)

 由上面的代码可以看出来:

operator new 实际也是通过malloc来申请空间,如果malloc申请空间成功就直接返回,否则执行用户提供的空间不足应对措施,如果用户提供该措施就继续申请,否则就抛异常;

operator delete 最终是通过 free 来释放空间的

五、new和delete的实现原理

1、内置类型

如果申请的是内置类型的元素,new 和 malloc,delete 和 free 基本类似;

不同的地方是:new / delete 申请和释放的是单个元素的空间,new[ ] / delete[ ] 申请的是连续的空间,而 new 在申请失败的时候会抛异常,malloc 会返回 NULL;

2、自定义类型

           1、调用operator new 函数申请空间;

           2、在申请的空间上执行构造函数,完成对象的构造; 

           1、在空间上执行析构函数,完成对象中资源的清理工作;

           2、调用 operator delete 函数释放对象的空间; 

            1、调用operator new[ ]函数,在operator new[ ]中实际调用 operator new 函数完成N个对象空间的申请;

            2、在申请的空间上执行N次构造函数;

            1、在释放的对象空间上执行N次析构函数,完成N个对象的资源清理;

            2、调用 operator delete[ ] 释放空间,实际在operator delete[ ]中调用 operator delete 来释放空间;

  • new的原理
  • delete的原理
  • new T[N]的原理
  • delete[ ]的原理

六、定位new表达式(placement-new)

定位 new 表达式在已经分配的原始内存空间中调用构造函数初始化一个对象;

使用格式:

new(place-address) type 或者 new (place-address) type(initializer-list)

place-address 必须是一个指针,initializer-list 是类型的初始化列表

使用场景:

定位 new 表达式在实际中一般是配合内存池使用。因为内存池分配出的内存没有初始化,所以如果是自定义类型的对象,需要使用 new 的定义表达式进行显示调构造函数并进行初始化;

class TestT {
public:
	TestT()
		:_data(0)
	{
		cout << "TestT()" << endl;
	} 
	~TestT()
	{
		cout << "~TestT()" << endl;
	}
private:
	int _data;
};
void Test() {
	TestT* pt = (TestT*)malloc(sizeof(TestT));

	new(pt) TestT;
}

七、malloc / free 和 new / delete 的区别

1、相同点:

  • 都是从堆上申请空间,并且需要用户手动释放;

2、不同点:

  • malloc 和 free 是函数, new 和 delete 是操作符;
  • malloc 申请的空间不会初始化,new 可以进行初始化;
  • malloc 申请空间时,需要手动计算空间的大小并传递, new 只需要跟上空间的类型即可;
  • malloc 的返回值为 void* ,在使用时必须进行强制转化,new 不需要;
  • malloc 申请空间失败时,返回的是 NULL,因此使用期间必须进行判空,new 不需要,但是 new 需要捕获异常;
  • 申请自定义类型对象时,malloc / free 只会开辟空间,而 new / delete 在申请和释放空间的时候,会调用构造 / 析构 函数;
  • new / delete 比 malloc / free 的效率稍微低一些,因为 new / delete 的底层封装了 malloc / free;
发布了79 篇原创文章 · 获赞 28 · 访问量 7770

猜你喜欢

转载自blog.csdn.net/weixin_43753894/article/details/99709049
今日推荐