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


Insert picture description here

1. C/C++ memory distribution

05-C language advanced-dynamic memory management This blog introduces the case of dynamic memory management and memory leaks in C language in detail.
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 to be noted:

  1. The stack is also called the stack, non-static local variables/function parameters/return values, etc. The stack grows downward.
  2. The memory mapped segment is an efficient I/O mapping method 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 up.
  4. Data segment-stores global data and static data.
  5. Code segment-executable code/read-only constant .

Two, C/C++ memory management mode

2.1 Dynamic memory management methods 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 repeat it

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

Insert picture description here

  • Malloc is to apply for a piece of continuous available space from the 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 move the data in the original memory to the new space.

There are two situations when realloc adjusts the memory space:

  • Situation 1: There is enough space after the original space. In case 1, if you want to expand the memory, add space directly after the original memory, and the data in the original space will not change.
  • Situation 2: There is not enough space after the original space. Expansion 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

Language memory management can continue to be used in C++, but in some places it is powerless and cumbersome to use, so C++ has proposed 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 picture description here
Note :

To apply for and release the space of a single element, use the new and delete operators and appear in pairs. To apply for and release continuous space, use new[] and delete[] and appear in pairs!

<2> New/delete operation custom type

Assume that 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 picture description here
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.
  • Use new to define new Dateand new Date(), but for Date type definition variables,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 operators for users to apply 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.
    Insert picture description here
    Insert picture description here
    By implementing these two global functions of aware, operator new is actually by malloc to apply for an empty room, if malloc space applications successfully direct return, or lack of implementation of response measures space provided by the user, if the user provides the measure would continue to apply, or Throw an exception. Operator delete finally releases space through free .

Three, the realization principle of new and delete

3.1 Built-in types

If the requested built-in type of space, new and malloc, delete and free are basically similar, the differences are:

  • New/delete applies for and releases the space of a single element;
  • new[]/delete[] applies for and releases continuous space;
  • New will throw an exception when the application fails, and malloc will return NULL when the application fails;

3.2 Custom type

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

Insert picture description here
Insert picture description here

Insert picture description here
Insert picture description here

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

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

They all apply for space from the heap and need to be released manually by the user.

The differences are:

  1. malloc and free are functions, new and delete are operators
  2. The space requested 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. New only needs to be followed by the type of space.
  4. The return value of malloc is void*, which must be forced when used. New is not required, 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, but new needs to catch exceptions
  6. When applying for a custom type object, malloc/free will only open up the space and will not call the constructor and> destructor. New will call the constructor to complete the initialization of the object after applying for the space, and delete will call the destructor before releasing the space. The function completes the cleaning of resources in the space

Five, memory leak

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

Memory leak : Memory leak refers to the situation where the program fails to release memory that is no longer used due to negligence or error. Memory leak does not mean the physical disappearance of the memory, but after the application allocates a certain segment of memory, because of a design error, it loses control of this segment of memory, which causes a waste of memory.

Harm : Memory leaks in long-running programs, such as operating systems, background services, etc., will cause memory leaks to 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 according to the needs of the program execution, and must be deleted by calling the corresponding free or delete after use. 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 Heap Leak will be generated.

Leakage of system resources:

Refers to the program using the resources allocated by the system. For example, sockets, file descriptors, pipes, etc. are not released using corresponding functions, resulting in a waste of system resources, severely reducing system performance and unstable system execution

5.3 How to avoid memory leaks

Prevention before the
event -smart pointers, error checking afterwards-leak detection tools

Guess you like

Origin blog.csdn.net/qq_40076022/article/details/114756387