C++ dynamic allocation (usage and difference between new and malloc)

Reference: https://blog.csdn.net/zhong29/article/details/80930919
https://blog.csdn.net/nyist_zxp/article/details/80810742

1. malloc and free
1. Function declaration:
void *malloc(int size);
description: malloc applies to the system to allocate size bytes of memory space, and the return type is void*;

2. Use

int* p;
p = (int*)malloc(sizeof(int));

free(p);//释放内存

Malloc function use note:
1) Malloc returns an indeterminate type pointer, so you need to do a forced type conversion before returning, otherwise the compilation error will occur;

2) Malloc only allocates memory and does not initialize it. The value in its memory space may be random. If the allocated space has not been used before, then each value may be 0. On the contrary, various values ​​may be left in the space.

3). The actual parameter is the size of bytes that need to be allocated. If malloc(1), then the system only allocates 1 byte of memory space. At this time, note that if an int value is stored in this space, due to the int type Occupies 4 bytes, then there are 3 bytes of unallocated space, and the system will allocate 3 bytes of space backwards in turn on the basis of the 1 byte that has been allocated, and this will occupy "others The original value of "others" is cleared in the 3 byte space of "."

4) When the allocated space is no longer used, use the free function to release this memory space.

5). The memory space pointed to by the pointer is released instead of the pointer itself. The pointer still exists after release, (for example, a variable like a pointer will only be destroyed at the end of the program) such as:

int* p;
p = (int*)malloc(sizeof(int));

free(p);

int a = 10;
p = &a;//指针依旧存在且可以被赋值

3. The working mechanism of the malloc function
1) When the malloc function is called, the malloc function looks for a memory block that meets the demand along the free linked list (existing in the memory heap), and then allocates the memory block of the required size to the user, and the rest Return to the linked list.

2) When calling the free function, it connects the memory block released by the user to the free chain.

3) After the malloc function is called or called multiple times, the free linked list will be divided into many small memory fragments. When the user applies for a larger memory space, there may not be a memory block that meets the demand on the free linked list. At this time, The malloc function requests a delay, organizes the small memory fragments in the free linked list into a large memory block, and finally returns.

4) If the memory block that meets the requirements cannot be obtained, the malloc function will return a NULL pointer. Therefore, when calling malloc to dynamically apply for a memory block, the return value must be judged.

Two, new and delete
1, new
1) Format:
new 类型名T(初始化参数列表)

2) Function:
During the execution of the program, apply for memory space for storing T-type objects, and assign initial values ​​according to the initial value list.

3) Result:
Achievement-"T-type pointer points to the newly allocated memory;
failure-"throw an exception.

Example:

//开辟单地址空间
int *p = new int;  //开辟大小为sizeof(int)空间
int *q = new int(5); //开辟大小为sizeof(int)的空间,并初始化为5。
//开辟数组空间
//一维
int *a = new int[100]{
    
    0};//开辟大小为100的整型数组空间,并初始化为0。
//二维
int (*a)[6] = new int[5][6];
//三维
int (*a)[5][6] = new int[3][5][6];
//四维及以上以此类推。

2. Delete
1) Format:
delete 指针p

2) Function: To
release the memory
p pointed to by the pointer p must be the return value of the new operation

3) Example:

//释放单个int空间
int *a = new int;
delete a;
//释放int数组空间
int *b = new int[5];
delete []b;

3. The difference between the two
1. The attributes
new and delete are C++ keywords and need to be supported by the compiler; malloc and free are library functions and need header file support.

2. Parameters
There is no need to specify the size of the memory block when using the new operator to apply for memory allocation. The compiler will calculate it according to the type information. And malloc needs to explicitly indicate the size of the required memory.

3. When the
memory allocation of the return type new operator succeeds, it returns a pointer of the object type. The type strictly matches the object and no type conversion is required. Therefore, new is an operator that conforms to type safety. While malloc memory allocation is successful, it returns void *, and the void* pointer needs to be converted to the type we need through forced type conversion.

4. The custom type
new will first call the operator new function to apply for enough memory (usually the bottom layer is implemented using malloc). Then call the constructor of the type, initialize the member variables, and finally return a pointer to the custom type. delete first calls the destructor, and then calls the operator delete function to release the memory (usually the bottom layer is implemented using free).

malloc/free is a library function, which can only dynamically apply and release memory, and cannot force it to do custom type object construction and destruction.

5. Overloading
C++ allows custom operator new and operator delete functions to control the allocation of dynamic memory.

6, the memory area
new does two things: allocate memory and call the constructor of the class, delete is: call the destructor of the class and release the memory. And malloc and free just allocate and release memory.

The new operator dynamically allocates memory space for the object from the free store, while the malloc function dynamically allocates memory from the heap. The free storage area is an abstract concept of C++ based on the new operator. Any memory application through the new operator is the free storage area . The heap is a term in the operating system. It is a special memory maintained by the operating system for the dynamic allocation of program memory. The C language uses malloc to allocate memory from the heap and free to release the allocated corresponding memory. The free storage area is not equal to the heap. As mentioned above, the layout new does not need to be located in the heap.

7. Allocation failure When the
new memory allocation fails, a bac_alloc exception will be thrown (try-catch is required). Malloc returns NULL when it fails to allocate memory.

8. Memory leaks
Memory leaks can be detected for both new and malloc, and new can specify which line of which file is, but malloc is not.

Guess you like

Origin blog.csdn.net/qq_43530773/article/details/113895903