What Is Dynamic Memory Allocation?
In the c / c ++ language, writing a program sometimes cannot determine how large the array should be defined, so at this time when the program is running, it needs to dynamically obtain more memory space from the system as needed. The so-called dynamic memory allocation refers to a method of dynamically allocating or reclaiming storage space to allocate memory during program execution. Dynamic memory allocation does not require pre-allocation of storage space like static memory allocation methods such as arrays. Instead, the system allocates them in real time according to the needs of the program, and the size of the allocation is the size required by the program.
- C language allows the establishment of a dynamic memory allocation area to store some temporary data. This data does not have to be defined in the declaration part of the program, nor does it need to be released when the function ends. In C language, dynamic memory allocation is achieved through library functions provided by the system, mainly malloc, calloc and free functions.
new Dynamic memory allocation new
- The operator new is used to request dynamic storage space from the system, and the first address is used as the result of the operation. Its use form is:
- Pointer variable = new data type;
- E.g:
- int * p = new int
- The role of this statement is to apply an int variable (4 bytes) from memory with new, and assign the first address of the variable to the pointer variable p.
- The initial value of the variable created by new is arbitrary, and it can also be initialized while allocating memory with new. The use form is:
- Pointer variable = new data type (initial value).
delete Dynamic memory allocation delete
- Heap memory can be allocated according to requirements, and the program's memory requirements may change at any time. Sometimes the program may no longer need the memory space allocated by new when the program is running, and the program has not finished running. At this time, the previously occupied Of memory space is released to heap memory and later reallocated for use by other parts of the program. The operator delete is used to release the memory space allocated by new and delete the created object. Its use form is:
- delete pointer variable;
- The pointer variable holds the first address of the memory allocated by new. [2]