C/C++ memory management - C/C++ memory management methods, implementation principles of new and delete, and memory leaks


insert image description here

1. C/C++ memory distribution

05-C language advanced - dynamic memory management This blog details the dynamic memory management of C language and the case of memory leak
Linux concept - process address space This blog introduces the process address space

For C/C++, the memory distribution is shown in the following figure:
/C

In C/C++, the address space is divided into kernel space, stack, memory mapping area, heap, data segment, and code segment . The following points need attention:

  1. The stack is also called the stack, non-static local variables/function parameters/return values, etc. The stack grows downward.
  2. Memory-mapped segments are efficient I/O-mapping methods for loading a shared dynamic memory library . Users can use the system interface to create shared shared memory for inter-process communication.
  3. The heap is used for dynamic memory allocation when the program is running , and the heap can grow.
  4. Data segment – ​​stores global data and static data.
  5. code segment – ​​executable code/read-only constant .

2. C/C++ state memory management

2.1 Dynamic memory management in C language (malloc/calloc/realloc and free)

05-C language advanced - dynamic memory management This blog introduces the dynamic memory management of C language in detail, this article will not go into details

Q1: What is the difference between malloc/calloc/realloc?

insert image description here

  • malloc is to apply for a continuous available space from memory;
  • The difference between calloc and malloc is that each space applied for is initialized to 0;
  • On the basis of adjusting the size of the original memory space, the realloc function will also move the data in the original memory to the new space.

There are two situations in which realloc adjusts the memory space:

  • Case 1: There is enough space after the original space. In case 1, to expand the memory, add space directly after the original memory, and the data in the original space does not change.
  • Case 2: There is not enough space after the original space. Extension method: Find another contiguous space of suitable size on the heap space to use. This function returns a new memory address.

2.2 C++ memory management method

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

<1> new/delete operation built-in type

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

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

	//动态申请10个int类型的空间
	int* ptr6 = new int[10];

	delete ptr4;
	delete ptr5;
	delete[] ptr6;
}

insert image description here
Note :

To allocate and free space for a single element, use the new and delete operators in pairs, allocate and free contiguous space, use new[] and delete[] in pairs!

<2> new/delete operation custom type

Suppose the Date class is as follows

//2.2.2
class Date
{
    
    
private:
	int _year;
	int _month;
	int _day;
public:
	Date(int year = 1900, int month = 1, int day = 1)
		:_year(year)
		, _month(month)
		, _day(day)
	{
    
    
		cout << "Date(int yaer = 1900, int month = 1, int day = 1)"<<endl;
	}
	~Date()
	{
    
    
		cout << "~Date()" << endl;
	}
};

We use malloc, new to apply for space, free and delete to release space

void Test4()
{
    
    
	//申请单个Date类型的空间
	Date* d1 = (Date *)malloc(sizeof(Date));
	//申请10个Date类型的空间
	Date* d2 = (Date *)malloc(sizeof(Date) * 10);
	free(d1);
	free(d2);
	cout << "--------------" << endl;
	//申请单个Date类型的空间
	Date* d3 = new Date;
	//申请10个Date类型的空间
	Date* d4 = new Date[10];
	delete d3;
	delete[] d4;
}

insert image description here
Notice

  • When applying for a space of a custom type, new will call the constructor, delete will call the destructor, but malloc and free will not.
  • Using new can define new Dateand new Date(), but for Date type variable,Yes Date d1but not Date d1(), because it will be recognized as a function declaration by the system

2.3 operator new and operator delete functions (emphasis)

  • new and delete are the operators for dynamic memory application and release by the user , and operator new and operator delete are global functions provided by the system
  • new calls the operator new global function at the bottom layer to apply for space, and delete uses the operator delete global function at the bottom layer to release the space.
    insert image description here
    insert image description here
    Through the implementation of the above two global functions, operator new actually applies for space . If the malloc application space is successful, it returns directly. Otherwise, the countermeasures provided by the user for insufficient space are executed. If the user provides this measure, continue to apply, otherwise Just throw an exception. operator delete finally releases space through free .

Third, the realization principle 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 differences are:

  • new/delete applies and releases the space of a single element;
  • new[]/delete[] applies and releases continuous space;
  • new throws an exception when the application fails, and returns NULL when malloc fails;

3.2 Custom Types

<1> The principle of new/new[] and delete/delete[]

insert image description here
insert image description here

insert image description here
insert image description here

Fourth, the difference between malloc/free and new/delete

What malloc/free and new/delete have in
common are:

All of them apply for space from the heap and need to be released manually by the user.

The difference is:

  1. malloc and free are functions, new and delete are operators
  2. The space applied by malloc will not be initialized, new can be initialized
  3. When malloc applies for space, you need to manually calculate the size of the space and pass it, and new only needs to follow the type of space.
  4. The return value of malloc is void*, which must be cast when used, and new is not needed, because new is followed by the type of space
  5. When malloc fails to apply for space, it returns NULL, so it must be empty when using it, new does not need it, 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, while 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. The function completes the cleanup of resources in the space

5. Memory leaks

5.1 What is a memory leak and the harm of memory leak?

Memory Leak : A memory leak is a situation in which a program fails to free memory that is no longer in use due to an oversight or error. Memory leak does not mean the physical disappearance of memory, but after the application allocates a certain segment of memory, it loses control of the segment of memory due to a design error, resulting in a waste of memory

Harm : Memory leaks occur in long-running programs, such as operating systems, background services, etc., and memory leaks will cause slower and slower responses and eventually freeze.

5.2 Classification of memory leaks

Heap leak:

Heap memory refers to a piece of memory allocated from the heap through malloc / calloc / realloc / new, etc., according to the needs of program execution. After use, it must be deleted by calling the corresponding free or delete. Assuming that the design error of the program causes this part of the memory to not be released, then this part of the space will no longer be used in the future, and a Heap Leak will occur.

System resource leakage:

Refers to the program using the resources allocated by the system, such as sockets, file descriptors, pipes, etc. are not released using the corresponding functions, resulting in a waste of system resources, which can seriously reduce system performance and lead to unstable system execution.

5.3 How to avoid memory leaks

Pre-prevention - smart pointers
Post-event troubleshooting - leak detection tools

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324149431&siteId=291194637