Dynamic memory allocation is determined only when the memory size is allocated at runtime, which is generally allocated in the heap. C language functions related to dynamic memory allocation.
Malloc
# Include <stdlib. h>
Void * malloc (size_t size );
The usage of malloc is direct. A successful malloc call returns the allocated size memory pointer. If a failure occurs, null is returned and the error code is set to enomem.
It is often used to forcibly convert the void pointer returned by malloc into memory and then assign it to the memory pointer, which is not necessary, when assigning values, the C language can automatically convert void pointers to corresponding pointers.
Calloc
# Include <stdlib. h>
Void * calloc (size_t NR, size_t size );
Calloc can allocate Nr memory space of a size, which is generally used for the allocation of a group of struct.
So what is the difference between calloc and malloc? Aside from the NR parameter (malloc can also set the parameter to Nr * size to achieve the same effect), the most critical difference is that the memory allocated by malloc is not necessarily initialized, calloc initializes all allocated memory to 0.
Realloc
# Include <stdlib. h>
Void * realloc (void * PTR, size_t size );
The realloc function re-allocates the size of the memory space pointed to by PTR to size and returns the new first memory address. For specific implementation, the function first tries to perform padding directly after the allocated memory. If the space is sufficient, the function returns the original address. If not, the system looks for a new space and malloc size byte, and then moves the original content to the new memory address. Therefore, the return value of the function may be the same as that of the original pointer, it may also be different.
In addition, if the size parameter is 0, the function has the same effect as the free function. If PTR is null, the function works the same way as malloc ~
Free
# Include <stdlib. h>
Void free (void * PTR );
Release the memory space applied by the first three functions. The most typical issue about free is memory leakage (Memory Leak ). Therefore, the memory allocated by the first three allocation functions must be free.