Advanced C language-basic knowledge of dynamic memory management

Advanced C language-basic knowledge of dynamic memory management

Why is there a concept of dynamic memory management? Because we usually define an array, it's all like this:

int num[10];

We need to know that the storage of arrays is to open up storage space on the stack, and the size of the stack is only 1-2MB, which is very small, and the program runs not only with arrays, but also other local variables and function calls on the stack. So when there is too much data in the array, it will involve the problem of stack overflow, and the size of the array cannot be changed after it is defined, so the concept of dynamic memory is introduced, because dynamic data is not stored on the stack, but on the heap , And the heap is much larger than the size of the stack. Generally, it is 4GB under a 32-bit operating system, and the memory can be dynamically divided, using as many points as possible. (All the following functions are in the header file stdlib.h )
1. The malloc function of the first function of dynamic memory planning.
Function parameter (1): the number of bytes , that is, how many bytes to allocate. The return value is an untyped address , namely void *.
Function prototype: void malloc( size_t size );
Of course, when the memory is allocated and not initialized, it stores a random value.
2. The second function calloc function of dynamic memory planning.
Function parameters (2): the number of data and the number of bytes occupied by a data (ie int 4 bytes, char 1 byte...). The return value is an untyped address , namely void
.
Function prototype: void calloc( size_t num, size_t size );
Of course, when the memory is allocated and not initialized, 0 is stored by default, which is the most essential difference from malloc.
3. The third function realloc function of dynamic memory planning.
Function parameters (2): the pointer name and the number of bytes to be re-allocated. The return value is an untyped address , namely void
.
Function prototype: void *realloc( void *memblock, size_t size );
Reminder: It is recommended that you do not rush to assign the return value to the previous address pointer after using this function to prevent data loss.
The fourth function 4. Dynamic memory programming free function of
the heap memory and stack memory is not the same, because the data stack of executing the program will automatically release, and the heap is not the same, it does not automatically release, if you do not Freeing will cause a memory leak (that is, the less memory is used), so there is a free function.
Function parameter (1): the memory address to be released (that is, the address pointed to by the pointer). No return value.
Function prototype: void free( void *memblock );
This function will release the dynamic memory with the address pointed to by the pointer as the first address .

Guess you like

Origin blog.csdn.net/qq_45841205/article/details/110244692