[C++] C/C++ memory management - new, delete


ヾ(๑╹◡╹)ノ" People always have to pay for their past lazinessヾ(๑╹◡╹)ノ"
insert image description here


1. C/C++ memory distribution

Code display:

#include <iostream>
int a = 1;//a在静态区(数据段)
static int b = 1;//b在静态区(数据段)
int main()
{
    
    
	static int c = 1;//c在静态区(数据段)
	int d = 1;//d在栈区
	int num[10] = {
    
     1, 2, 3 };//num在栈区
	const char c[] = "abcd";//c和*c在栈区;常量字符串的内容拷贝一份,赋值给数组c,所以这个字符串不是在常量区
	const char* p = "abcd";//p在栈区,在栈区创建一个变量p,来储存常量字符串的地址
	//*p在常量区:*p是p所指向的内容,常量字符串,
	int* p1 = (int*)malloc(sizeof(int) * 4);//p1在栈区,*p1是指针指向的地址,这个地址在堆区
	int* p2 = (int*)calloc(4, sizeof(int));
	int* p3 = (int*)realloc(p2, sizeof(int) * 4);
	free(p1);
	free(p2);
	return 0;
}

Stack area: local variable
sizeof (array name): the size of the entire array
sizeof (string): note '\0'

  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 mappings for loading a shared dynamic memory bank. Users can use the system interface to create shared shared memory for inter-process communication. (learn)
  3. The heap is used for dynamic memory allocation when the program is running, and the heap can grow upwards.
  4. Data segment - stores global and static data.
  5. Code section (constant area) - executable code/read-only constants.

2. Dynamic memory management in C/C++

2.1 Dynamic memory management in C language

malloc/calloc/realloc/free
interview questions: The difference between malloc/calloc/realloc?

2.2 C++ memory management method

C++ implements dynamic memory management through new and delete operators. [New dynamically opened space does not need to check whether it is successfully opened]

  • For built-in types, there is no difference
  • The difference is in the custom type, C++ custom type: [new] create space + call constructor initialization [delete] call destructor to clean up resources + release space [creation failure: throw exception]; C language: [malloc] only create space [free] only releases space [failure to create: return null pointer]
int main()
{
    
    
	int* p1 = new int;//new 1个对象
	int* p2 = new int[10];//new 10个对象
	int* p3 = new int(10);//new 1个对象,值初始化为10
	int* p4 = new int[6]{
    
     1, 2, 3, 4 };//new 6个对象,值初始化分别为1、2、3、4、0、0(C++11才支持)
	delete p1;//new出来的
	delete[] p2;//new[]出来的
	delete p3;//new出来的
	delete[] p4;//new[]出来的
	//注意要匹配,如果不匹配,不一定会报错。但是还是要匹配
	return 0;
}

Notice: (1) To apply for and release the space of a single element, use the new and delete operators to apply for and release continuous space, use new[] and delete[], note: match and use.
(2) When applying for a custom type of space, new will call the constructor, delete will call the destructor, but malloc and free will not.

Three, operator new and operator delete functions

3.1 operator new and operator delete functions

  • 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 layer to apply for space, and delete uses the operator delete global function at the bottom layer to release space .
  • operator new actually applies for space through malloc. If malloc successfully applies for space, it will return directly. Otherwise, it will execute the countermeasures provided by the user for insufficient space. 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.2 Class-specific overloading of operator new and operator delete (understand)

  • Applying for space to the heap is faster than applying for space to the memory pool.
  • Overload the exclusive operator new/operator delete function, implement the function, and apply for space from the memory pool. It is equivalent to applying for space to the memory pool faster. Use the memory pool to apply and release memory to improve efficiency.

Fourth, the realization principle of new and delete

built-in type

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

custom type

  • The principle of new
  1. Call the 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 of N object spaces
  2. Execute the constructor N times on the requested space
  • The principle of delete[]
  1. Execute N times of 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

Five, positioning new expression (placement-new) (understand)

Positioning the new expression is to call the constructor to initialize an object in the allocated original memory space.
Use the format:
new (place_address) type or new (place_address) type(initializer-list)
place_address must be a pointer , initializer-list is the initialization list of the type
scenes to be used:
Positioning new expressions are generally used in conjunction with memory pools in practice . Because the memory allocated by the memory pool is not initialized, if it is an object of a custom type, it needs to use the definition expression of new to explicitly call the constructor for initialization.
new(obj)Date(3) is equivalent to: Date* obj = new Date(3)

6. Interview questions

The difference between malloc/free and new/delete[Usage 1-4 and Difference 5-6]
The common point between malloc/free and new/delete is that they both 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, but new can be initialized
  3. When malloc applies for space, you need to manually calculate the size of the space and pass it on. New just needs to follow it with the type of space. If there are multiple objects, specify the number of objects in []
  4. The return value of malloc is void*, which must be forced when used, and new does not need it, because new is followed by the type of space
  5. When malloc fails to apply for space, it returns NULL, so it must be judged as empty when using it, new does not need it, but new needs to catch exceptions
  6. When applying for a custom type of 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 Complete the cleanup of resources in the space

memory leak

  • What is a memory leak, the harm of memory leaks
  1. What is a memory leak: A memory leak refers to a situation in which a program fails to release memory that is no longer in use due to negligence or error. A memory leak does not refer to the physical disappearance of memory, but rather the loss of control over a certain segment of memory due to a design error after the application allocates a certain segment of memory, resulting in a waste of memory .
  2. Hazards of memory leaks: Memory leaks occur in long-running programs, which have a great impact, such as operating systems, background services, etc. Memory leaks will lead to slower and slower responses, and eventually freeze.
    A memory leak is a lost pointer
  • Classification of memory leaks (understanding)
  1. Heap memory leak (Heap leak): Heap memory refers to a piece of memory allocated from the heap through malloc / calloc / realloc / new, etc. during program execution as needed. 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 Heap Leak will occur.
  2. System resource leakage : Refers to the resources allocated by the system used by the program, such as sockets, file descriptors, pipes, etc., which are not released using the corresponding functions, resulting in a waste of system resources, which can seriously lead to reduced system performance and unstable system execution.
  • How to avoid memory leaks
  1. Good design specifications in the early stage of the project, develop good coding standards, and remember to release the memory space that matches. ps: This ideal state. But if you encounter an exception, even if you pay attention to release, there may still be problems. It needs to be managed by the next smart pointer to be guaranteed.
  2. Use RAII ideas or smart pointers to manage resources.
  3. Some company internal specifications use internally implemented private memory management libraries. This library comes with options for memory leak detection.
  4. Something went wrong using a memory leak tool to detect. ps: However, many tools are not reliable enough, or the fees are expensive.
    Memory leaks are very common, and there are two solutions: 1, pre-prevention type. Such as smart pointers, etc. 2. Post-event error checking type. Such as leak detection tools.

Supplementary knowledge:
Compiler optimization problem : (constructor) [optimization depends only on the compiler]

  • Anonymous object : the life cycle is only this line, [class: the constructor and destructor will be called on this line]kind()[Example: Date() ]
  • Usage scenario : when only one function in the class needs to be calledclass.function(eg: Date().num(10) )
  1. In an expression: Consecutive construction + copy construction will be optimized
    f(Date());//Date(), perform construction, and then immediately () copy construction, the compiler optimizes. Just optimize directly to a constructor. inside the one-line expression
  2. In an expression: consecutive copy constructions will also be optimized
    Date ret = f(x); f(x) returns by value, a temporary variable, a copy construction, assigning a value to
    ret for a copy construction. Then optimized.

Summarize

The above is what I will talk about today. This article introduces C/C++ memory distribution, dynamic memory management methods, operator new and operator delete functions, and the implementation principles of new and delete in detail. Hope to help friends!

Guess you like

Origin blog.csdn.net/m0_57388581/article/details/132500250
Recommended