C++---Dynamic Memory Management

C/C++ memory distribution
Insert picture description here
Stack: store non-static local variables, function parameters, and return values.
Memory mapping segment: dynamic library.
Heap: Dynamic memory allocation when the program is running.
Data segment: store global variables and static data.
Code segment: executable code, read-only constant.

Dynamic memory management in C language

  • malloc function

  • void* malloc(size_t number)

  • Dynamically apply for a continuous area with a length of numbre bytes in the heap, and return the first address of the area, but the return type is void*. It needs to be type converted during use, and the block area is not initialized. If you want To initialize it as a whole, it can be initialized in combination with the memset function.

  • void memeset(void* buf,int c,int count), buff is the first address of the area, c is the initialized value, and count is the size of the area.

  • note When malloc applies for space, it may fail, so when using malloc to apply for the space, it needs to be nullified.

  • calloc function

  • void* calloc(size_t number,size_t size)

  • number is the number of elements in the application space, size is the size of each element, and the total size of the application space with calloc is number*size.

  • When calloc applies for space, it initializes its area by default, and the default initialized value is 0.

  • note Calloc may fail when applying for space, so when using the space requested by calloc, it needs to be nullified.

  • realloc function

  • void* realloc(void* buff,size_t new_size)

  • Realloc adjusts the size of the space requested by malloc, buff is the first address of the space, and new_size is the size of the original space. new_size can be larger or smaller than the original space.

  • note When realloc applies for space, it may fail, so when using realloc to apply for the space, it needs to be nullified.

  • The difference between malloc/calloc/realloc

  • The malloca function cannot initialize the requested space, and calloc will initialize the requested space at the same time. calloc initializes the pointer type to a null pointer and the data type to 0. If realloc shrinks the memory, part of the reduced data will be lost. When it expands the memory, the compiler will first expand behind its original memory. If the location is insufficient, it will reopen a new memory space and finally move the data. , The returned pointer is likely to be a new address.

  • No matter which function is used to apply for space, the applied space is released with free. void free(void* buff), buff is the first address of the application space. After releasing the space with free, you need to manually assign the first address of the original space to NULL to avoid wild pointers.

C++ memory management operations

  • new / delete apply for built-in types
void TestFunc()
{
    
    
	int* p1 = new int; //申请int类型的空间;
	int* p2 = new int(3); //申请一个int类型的空间并对其初始化为3;
	int* p3 = new int[3]; //申请3个int类型的空间,相当于申请int类型的数组
}
  • Apply for a custom type
class Date
{
    
    
public:
	Date()
	{
    
    	
		cout<<"Date()构造函数"<<endl;
	}
	~Date()
	{
    
    
		cout<<"~Date()析构函数"<<endl;
	}
private: 
	int d;
};
void TestFunc()
{
    
    
	//malloc申请1个自定义类型的空间
	Date* p1 = (Date*)malloc(sizeof(Date));
	free(p1);
	//new申请一个自定义类型的空间
	Date* p2 = new Date;
	delete p2;
}

Insert picture description here
In the application space, the space that is busy with new application will call the constructor, malloc will only apply for a space, delete will call the destructor, and free will not.

Note: When applying for space and releasing space, new and delete, malloc and free must appear in pairs. Otherwise, an error will occur.

new[]/delete[]

  • new[] applies for multiple spaces at the same time, and delete[] releases multiple spaces at the same time.
int* p1 = new int[10]; //申请10个int型空间
delete[] p1;
Date* p2 = new Date[10]; //申请10个自定义类型空间
delete[] p2; 

The underlying implementation principle of new

New application space will be performed in two steps. The first step is to apply for space, and the second step is to call the constructor for initialization.

  • The first step: apply for space, the underlying code
void* operator new(size_t size)
{
    
    
	//底层调用malloc函数循环申请空间
	malloc循环申请空间;
	if(申请失败)
		提供空间不足的措施;
	else
		直接退出;
}
  • Step 2: Call the constructor to complete the initialization operation.

The underlying principle of delete

  • void operator delete()。
  • The first step is to call the destructor to release the resources in the object
  • In the last sentence before the end of releasing the object resources, call the free() function to release the object space.

Operator new actually applies for space through malloc. If malloc successfully applies for space, it will return directly. Otherwise, the user-provided space shortage countermeasures will be executed. If the user provides such measures, the application will continue, otherwise an exception will be thrown. Operator delete ultimately releases space through free.

new[ ]Underlying principle

  • void* operator new[](size_t size) internally calls the void* operator new(size_t size) function.
  • Call the operator new[] function, and actually call the operator new function in operator new[] to complete the application for multiple object spaces.
  • Execute the constructor multiple times on the application space.

delete[] underlying principle

  • void operator delete[]
  • Call the destructor multiple times to complete the resource cleanup of multiple objects.
  • Executing operator delete[] to release space is actually calling the operator delete function to release space.

Guess you like

Origin blog.csdn.net/qq_42708024/article/details/104295898