C/C++ memory management related knowledge points

1. Memory distribution

C/C++ divides memory into four areas: stack area, heap area, static area (data segment), and constant area (code segment).

Stack area: A structure used to store temporary information when a function is called, storing local variables, function parameters, return data, return addresses, etc. allocated for runtime functions.

Heap area: A place where programmers use malloc or new to apply for storage. (dynamic memory allocation)

Static area: static modified data, global data, storage location.

Constant area: Constants that will not change are stored here.


Look at the following piece of code and answer the questions:

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

Looking at the above piece of code, please answer the following:

Insert image description here
Insert image description here

2. new/delete keyword

2.1 Operating built-in types

int main()
{
    
    

	//动态申请一个int 类型的空间
	int* ptr1 = new int;
	delete ptr1;			//释放ptr1
	
	// 动态申请一个int 类型的空间,并初始化为 5
	int* ptr2 = new int(5);
	delete ptr2;		   //释放ptr2

	// 动态申请5个int 类型的空间
	int* ptr3 = new int[5];
	delete[] ptr3;         // 释放ptr3,注意怎么new的怎么delete

	 动态申请5个int 类型的空间,并初始化
	int* ptr4 = new int[5]{
    
     1,2,3 };
	delete[] ptr4;		   // 释放ptr4,注意怎么new的怎么delete

	return 0;
}

**Note: new corresponds to delete, new [] corresponds to delete []. **Cannot be used incorrectly.

Operation custom type

In addition to applying for and releasing space, new and delete will automatically call the constructor and destructor.

class A
{
    
    
public:
	A(int a = 0)
	{
    
    
		cout << "A()" << endl;
	}
	~A()
	{
    
    
		cout << "~A()" << endl;
	}

private:
	int _day;
	int _year;
	int _month;
};

int main()
{
    
    
	A* p1 = new A(1);  //一次构造
	delete p1;			//一次析构

	A* p2 = new A[5];  // 五次构造
	delete[] p2;       //五次析构

	

	return 0;
}

3. opeartor new and operator delete functions

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. .

Among them:
operator new : This function actually applies for space through malloc, and returns directly if the application is successful; when it fails, it tries to implement the insufficient space response strategy. If the user sets this measure, continue to apply for space, otherwise an exception is thrown.

operator delete : This function finally releases space through free().


Insert image description here
It can also be seen from this definition that free() is actually a rename, and the real function name is later.

4. New and delete principles

4.1 Built-in types

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

4.2 Custom types

  • The principle of new
    1. Call operator new to apply for space
    2. Execute the constructor on the applied space to complete the construction of the object.

  • 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 space of the object

  • newT[N] Principle
    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

  • delete[] Principle
    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.

The following example summarizes:
Insert image description here

5. Position new expression (placement-new)

The positioned new expression is to call the constructor to initialize an object in the allocated original memory space.

Usage syntax:
new (place_address) type or new (place_address) type(initializer-list)
place_address must be a pointer, and initializer-list is the initialization list of the type.


new(p1)A;    //如果A的构造函数有参数,此处需要传参
nwe(p2)A(10);  // 初始化参数为10

6. The difference between malloc/free and new/delete

What they have in common:
They all apply for space from the heap and need to be released manually.

difference:

  1. malloc and free are functions, new and delete are keywords.
  2. The space requested by malloc will not be initialized, and new can call the constructor to complete the initialization.
  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 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 a space type.
  5. When malloc fails to apply for space, it returns NULL, so it must be null when used. New does not need to, but it needs to catch the exception.
  6. When applying for a custom type, 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. Cleanup of resources in object space.

7. Memory leak

Relevant knowledge will continue to be added in the future. . .

Guess you like

Origin blog.csdn.net/weixin_45153969/article/details/132909867