C++ dynamic memory management (new and delete)

1. Dynamic memory management in C++

The C language memory management method can continue to be used in C++, but it is ineffective in some places and is more troublesome to use. Therefore, C++ has proposed its own memory management method: dynamic memory management through the new and delete operators.

1.1 New/delete operation built-in types

void Test()
{
    
    
	// 动态申请一个int类型的空间
	int* ptr4 = new int;

	// 动态申请一个int类型的空间并初始化为10
	int* ptr5 = new int(10);

	// 动态申请10个int类型的空间
	int* ptr6 = new int[10];
	//在动态申请10个int类型的空间的同时还可以初始化(后面加上一个中括号,在中括号内部赋初值)
	//{}内部如果什么都不写,默认为全0
	int* ptr7 = new int[3] {
    
    };
	//释放空间
	delete ptr4;
	delete ptr5;
	delete[] ptr6;
	delete[] ptr7;
}

Insert image description here

Note: To apply for and release space for a single element, use the new and delete operators . To apply for and release continuous space , use new[] and delete[] .
Note: Matching is used! Match to use! Match to use!

1.2 New and delete operations on custom types

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;
}

Note: When applying for a custom type of space, new will call the constructor, delete will call the destructor, but malloc and free will not.

2. operator new and operator delete functions

2.1 operator new and operator delete functions (emphasis)

new and delete are operators used by users to apply for and release dynamic memory. operator new and operator delete are global functions provided by the system . new calls the operator new global function at the bottom to apply for space, and delete uses the operator delete global function at the bottom to release space. .

The following is the official C++ implementation and explanation of the operator new and operator delete functions:

operator new : This function actually applies for space through malloc, and returns directly when malloc applies for space successfully; if the space application fails, try to implement insufficient space countermeasures. If the countermeasures are set by the user, continue to apply, otherwise an exception will be thrown.

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: This function finally releases space through 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;
}

From the implementation of the above two global functions, we know that operator new actually applies for space through malloc. If malloc successfully applies for space, it will return directly. Otherwise, the user-provided countermeasures for insufficient space will be executed. If the user provides this measure, it will continue to apply. Otherwise, it will Throw an exception. operator delete finally releases space through free.

3. Implementation principles of new and delete

3.1 Built-in types

If you apply for a built-in type of space, new and malloc, delete and free are basically similar. The difference is: new/delete applies for and releases the space of a single element, while new[] and delete[] apply for continuous space. Moreover, new will throw an exception when it fails to apply for space, and malloc will return NULL.

3.2 Custom types

  • The principle of new
  1. Call operator new function to apply for space
  2. Execute the constructor on the requested space to complete the construction of the object
  • The principle of delete
  1. Execute the destructor on the space to complete the cleanup of resources in the object
  2. Call the operator delete function to release the object's space
  • The principle of new T[N]
  1. Call the operator new[] function, and actually call the operator new function in operator new[] to complete the application for N object spaces.
  2. Execute the constructor N times on the requested space
  • The principle of delete[]
  1. Execute N destructors on the released object space to complete the cleanup of resources in N objects
  2. Call operator delete[] to release space. Actually call operator delete in operator delete[] to release space.

4. Common interview questions

4.1 The difference between malloc/free and new/delete

What malloc/free and new/delete
have in common is that
they both apply for space from the heap and require the user to release it manually.

The difference is:

  1. malloc and free are functions , new and delete are operators.
  2. The space requested by malloc will not be initialized, but new can be initialized.
  3. When malloc applies for space, you need to manually calculate the space size and pass it . New only needs to be followed by the type of space .
    If there are multiple objects, just specify the number of objects in [].
  4. The return value of malloc is void*, which must be forced when used. New does not need to, because new is followed by the type of space.
  5. When malloc fails to apply for space, it returns NULL , so it must be null when used. New does not need to, but new needs
    to catch exceptions.
  6. When applying for a custom type object, malloc/free will only open up space and will not call the constructor and destructor. New will call the constructor to
    complete the initialization of the object after applying for space, and delete will call the destructor before releasing the space. Complete
    the cleanup of resources in the space.

4.2 Memory leak

What is a memory leak and the dangers of memory leaks

What is a memory leak:
A memory leak refers to a situation where a program fails to release memory that is no longer in use due to negligence or error. Memory leaks do not mean the physical disappearance of memory, but that after the application allocates a certain segment of memory, it loses control of the memory segment due to design errors, thus causing a waste of memory.

The harm of memory leaks:
Memory leaks in long-running programs, such as operating systems, background services, etc., have a great impact. Memory leaks will cause the response to become slower and slower, and eventually freeze.

Guess you like

Origin blog.csdn.net/originalHSL/article/details/132036321