Introduction to C++ memory management | Review of malloc, realloc, calloc in C | Memory distribution | Memory management | new delete | operator new | operator delete

Table of contents

1. C/C++ memory distribution

1. Division of program memory area in C/C++

2. Dynamic memory management in C language

1.malloc/calloc/realloc/free

3. Dynamic memory management in C++

1.new/delete operation built-in type

2.New and delete operations on custom types

4. Operator new and operator delete functions

1.operator new and operator delete functions

5. Implementation principles of new and delete

1. Built-in types

2. Custom type

The difference between malloc/free and new/delete

Summarize


1. C/C++ memory distribution

1. Division of program memory area in C/C++

In the memory, the memory is divided into different areas to facilitate OS management. It is mainly divided into the following parts:

  • Kernel space (user code cannot read or write)
  • Stack (growing downward): Also called the stack, it stores non-static local variables, function parameters, return values, etc.
  • Memory mapping segment: It is an efficient IO mapping method, used to load a shared dynamic memory library. Users can use the system interface to create shared memory for inter-process communication.
  • Heap (growing upward): used for dynamic memory allocation while the program is running. The value from mallo/realloc... is on the heap
  • Data segment (also called static area): stores global variables and static variables
  • Code segment (constant area): stores executable code/read-only constants

 Where is char2 ? local variables on the stack      

* Where is char2 ? The name of the array is the address of the first element, char2 points to the address of a, *char2 points to a, on the stack
Where is  pChar3 ? local variables on the stack     
* Where is pChar3 ? Points to a character constant, in the code segment (constant area)
Where is    ptr1 ? local variables, on the stack
* Where is ptr1 ? Points to the value from mallo, on the heap

2. Dynamic memory management in C language

1.malloc/calloc/realloc/free

void Test ()
{
int* p1 = (int*) malloc(sizeof(int));
free(p1);
// 1.malloc/calloc/realloc的区别是什么?
int* p2 = (int*)calloc(4, sizeof (int));
int* p3 = (int*)realloc(p2, sizeof(int)*10);
// 这里需要free(p2)吗?  不需要
free(p3 );
}
  • malloc: Open up size bytes of memory. If the allocation is successful, it will return the starting address of this memory. If it fails, it will return a null pointer. The returned starting address is void * type.

  •  calloc: Open an address of num* type bytes and initialize it to 0. If size is 0, the return value depends on the specific library (not sure whether it is a null pointer), but the returned pointer cannot be dereferenced. If the development is successful, the starting address is returned and the type is void*. If the development fails, a null pointer is returned.

 

  • realloc: Change the size of the memory block pointed by ptr. The function moves the memory block to a new location and retains the smaller of the two original sizes. If ptr is a null pointer, the function is the same as malloc.

3. Dynamic memory management in C++

1.new/delete operation built-in type

void Test()
{
  // 动态申请一个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;
}

To apply for and release space for a single element, use the new and delete operators. To apply for and release continuous space, use new[] and delete[]. Note that the operators must match

2.New and delete operations on custom types

class A
{
public:
  //构造
 A(int a = 0)
 : _a(a)
 {
     cout << "A():" << this << endl;
  }

//注:在申请自定义类型的空间时,new会调用构造函数,delete会调用析构函数,而malloc与
free不会。

 ~A()
 {
 cout << "~A():" << this << endl;
 }
private:
 int _a;
};
int main()
{
 // new/delete 和 malloc/free最大区别是 new/delete对于【自定义类型】除了开空间
还会调用构造函数和析构函数
 A* p1 = (A*)malloc(sizeof(A));
 A* p2 = new A(1);
 free(p1);
 delete p2;
 // 内置类型是几乎是一样的
 int* p3 = (int*)malloc(sizeof(int)); // C
 int* p4 = new int;
free(p3);
delete p4;
 A* p5 = (A*)malloc(sizeof(A)*10);
 A* p6 = new A[10];
 free(p5);
 delete[] p6;
 return 0;
}

4. Operator new and operator delete functions

1.operator new and operator delete functions

new and delete are the operators for users to apply for and release dynamic memory . operator new and operator delete are
The global function 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.
Operator new actually applies for space through malloc . If malloc successfully applies for space, it will return directly. Otherwise, it will implement the insufficient space response measures provided by the user. If the user provides this measure, it will continue to apply, otherwise it will throw an exception. Operator delete finally releases space through free .

5. Implementation principles of new and delete

1. Built-in types

If you are applying 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, and new will throw an exception when it fails to apply for space, and malloc will return NULL .

2. Custom type

  • The principle of new

    1. Call operator new to apply for space

    2. Execute the constructor on the requested space to complete the construction of the object

  • delete principle

    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

  •     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 for N object spaces.
    2. Execute the constructor N times on the requested space
  • The principle of delete[]
   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. In fact, operator delete is called in operator delete[] to free up space.
Make space

The difference between malloc/free and new/delete

What malloc/free and new/delete have in common is that they both apply for space from the heap and require the user to release it manually. The differences are answered from the following two aspects: usage and underlying principles.

1. Usage

  • 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 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 of objects in [] .
  • 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.

2. Underlying principles

  • When malloc fails to apply for space, it returns NULL , so it must be null when used. New does not need to, but new requires
To catch exception
  •  When applying for a custom type object, 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. Complete the cleanup of resources in the space

Summarize

This chapter mainly summarizes the memory distribution in C/C++, as well as the usage of malloc, realloc, calloc functions, and new/delete operators.

Guess you like

Origin blog.csdn.net/jolly0514/article/details/131740626