The memory allocation functions commonly used in C language include malloc, calloc, and realloc. Among them, the most commonly used functions are malloc. Here we will briefly explain the differences and connections between the three.
1. Statement
All these three functions are in the stdlib. h library file and are declared as follows:
Void * realloc (void * ptr, unsigned newsize );
Void * malloc (unsigned size );
Void * calloc (size_t numElements, size_t sizeOfElement );
Their functions are similar in that they request memory allocation to the operating system. If the allocation is successful, the address of the allocated memory space is returned. If the allocation is not successful, NULL is returned.
2. Functions
Malloc (size): allocates a continuous area with a length of "size" bytes in the dynamic storage area of the memory, and returns the first address of the region.
Calloc (n, size): In the dynamic storage area of the memory, allocate n consecutive areas with the length of "size" bytes and return the first address.
Realloc (* ptr, size): increase or decrease the size of ptr memory.
It should be noted that realloc increases or decreases the ptr memory to size. In this case, the new space is not necessarily obtained by increasing or decreasing the length of the original ptr space, however, it is possible (especially when realloc is used to increase the memory space of ptr) to allocate a large space in a new memory area, copy the content of the original ptr space to the starting part of the new memory space, and then release the original space. Therefore, we generally need to use a pointer to receive the realloc return value. The following is an example of the realloc function.
#include
#include
int main(){//allocate space for 4 integersint *ptr=(int *)malloc(4*sizeof(int));if (!ptr){printf("Allocation Falure!\n");exit(0);}//print the allocated addressprintf("The address get by malloc is : %p\n",ptr);//store 10、9、8、7 in the allocated spaceint i;for (i=0;i<4;i++){ptr[i]=10-i;}//enlarge the space for 100 integersint *new_ptr=(int*)realloc(ptr,100*sizeof(int));if (!new_ptr){printf("Second Allocation For Large Space Falure!\n");exit(0);}//print the allocated addressprintf("The address get by realloc is : %p\n",new_ptr);//print the 4 integers at the beginningprintf("4 integers at the beginning is:\n");for (i=0;i<4;i++){printf("%d\n",new_ptr[i]);}return 0;}
The running result is as follows:
As can be seen from the above, the new space in this example is not allocated based on the original space, but is re-allocated with a large space, copy the content of the original space to the beginning of the new space.
3. connections between the three
Calloc (n, size) is equivalent to malloc (n * size). In realloc (* ptr, size), if ptr is NULL, realloc (* ptr, size) it is equivalent to malloc (size ).