malloc vs calloc vs realloc
Dynamic Memory Allocation refers to the method of allocating a block of memory and releasing it when the memory is not required at the time of running the program. A block of memory can be used to store values of simple or sub-scripted variables. In C Programming Language, there are four types of Dynamic Memory Allocation are exists:
malloc() function is used to allocate a single block of memory to store values of specific data type. It assigns the address of the first byte of the allotted space to a pointer.
sp= (type *)malloc(size);
where sp is the pointer variable, the type is a data type which is to be stored in memory, size is the number of bytes to be allotted.
calloc() function is used to allocate a multiple blocks of same size during the program execution. It is used to store the values of an array.
sp= (type *) calloc (n, m);
where sp is the pointer variable, the type is a data type which is to be stored in memory, n is the number of blocks to be allotted, m is the number of bytes in each block of memory.
realloc() function is used to reallocate the memory space which is previously allotted. It increases or reduces the allotted space at a later stage in a program.
where sp is the pointer variable, size is the number of bytes to be newly allotted.
free() function is used to release the memory space which is allotted using malloc() or calloc() or realloc() function.
where sp is the pointer which refers to the allotted space in memory.
What is the difference between malloc calloc and realloc?:
|1. malloc stands for memory allocations.||1. calloc stands for contiguous allocation||1. realloc stands for re-allocation.|
|2. malloc() is a function which is used to allocate a block of memory dynamically.||2. calloc() is a function which is used to allocate multiple blocks of memory.||2. realloc() is a function which is used to resize the memory block which is allocated by malloc or calloc before.|
|3. It is used to dynamically allocate a single large block of memory with the requied size||3. calloc() specifies the number of blocks of memory to be allocated.||3. When memory allocated previously is not sufficient, then more memory is required, the realloc method is used to re-allocate memory dynamically.
|4. Syntax: mp = (cast_type*) malloc(byte_size);||4. Syntax: cp= (int*) calloc(100, sizeof(int));||4. Syntax: rp = realloc(rp, newSize);|