C language commonly used in memory allocation function has malloc, calloc and realloc, such as three, of which, the most commonly used is malloc, here is a brief talk about the differences and relations between the three.
1. Statement
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);
They are similar in function to requesting memory allocations to the operating system, and if the allocation succeeds, returns the address of the allocated memory space and returns NULL if no allocation succeeds.
2. function
malloc (size): Allocates a contiguous region of length "size" in the dynamic store of memory, returning the first address of the region.
Calloc (n,size): Allocates n contiguous regions with length "size" bytes in the dynamic storage area of memory, returning the first address.
ReAlloc (*ptr,size): Increase or decrease the PTR memory size to size.
It is important to note that the realloc increases or shrinks the PTR memory to size, when the new space is not necessarily based on the original PTR space, increasing or decreasing the length, and possibly (especially when using realloc to increase the memory space of PTR) is to allocate a large space in a new memory area, then copy the contents of the original PTR space to the beginning of the new memory space, and then release the original space. Therefore, the return value of realloc is generally received with a pointer, and here is an example of the ReAlloc function.
#include
#include
int main ()
{
Allocate space for 4 integers
int *ptr= (int *) malloc (4*sizeof (int));
if (!ptr)
{
printf ("Allocation falure!\n");
Exit (0);
}
Print the allocated address
printf ("The address Get by malloc is:%p\n", PTR);
Store 10, 9, 8, 7 in the allocated space
int i;
for (i=0;i<4;i++)
{
Ptr[i]=10-i;
}
Enlarge the space for integers
int *new_ptr= (int*) realloc (ptr,100*sizeof (int));
if (!new_ptr)
{
printf ("Second Allocation for Large Space falure!\n");
Exit (0);
}
Print the allocated address
printf ("The address Get by ReAlloc is:%p\n", new_ptr);
Print the 4 integers at the beginning
printf ("4 integers at the beginning is:\n");
for (i=0;i<4;i++)
{
printf ("%d\n", New_ptr[i]);
}
return 0;
}
The results of the operation are as follows:
As can be seen from the above, in this example, the new space is not the original space for the base allocation, but the redistribution of a large space, and then copy the original space content to the beginning of the new space.
3, the three contact
Calloc (n,size) is equivalent to malloc (n*size), whereas in ReAlloc (*ptr,size), if PTR is null, then ReAlloc (*ptr,size) is the equivalent of malloc (size).
......................................................................................................................... .........