C language memory allocation function, Allocation Function
The C Language Standard Library provides three memory allocation functions, all of which are included in the header file <stdlib. h>.
1. malloc
Function prototype:
void *malloc( size_t size );
Parameters: Number of bytes to allocate memory size
Return Value: Pointer to the memory address. If an error occurs, NULL is returned.
Function: Allocate a memory space of the specified size.
Details: Memory spaceContinuousAndHeapSpace, need to useFree ()The function is manually released, and the space is junk data.
2. calloc
Function prototype:
void *calloc( size_t num, size_t size );
Parameters: 1. Number of memory to be allocated 2. number of bytes per memory
Return Value: Pointer to the memory address. If an error occurs, NULL is returned.
Function: Allocate a memory space of the specified size.
Details: Memory spaceContinuousAndHeapSpace, need to useFree ()The function is manually released, and the data in the space is initialized to 0.
3. realloc
Function prototype:
void *realloc( void *ptr, size_t size );
Parameters: 1. The object to change the space size 2. Change the original space size to size.
Return Value: Pointer to the memory address after the change. If the error is returned, NULL is returned.
Function: Change the size of an allocated space.
Details: Memory spaceContinuousAndHeapSpace, need to useFree ()Manually release the function.
The size can be larger than or smaller than the original size. When the size of the original space is greater than that of the original space, if there is sufficient memory allocation behind the original space, the size of the original space is expanded directly. Parameter 1 is equal to the return value.
If not, find another one that is large enough.ContinuousMemory Address, copy the content of the original address to the new address. Reclaim the original space and return the pointer of the new address.