Dynamic Memory Allocation in C using malloc(), calloc(), free() and
realloc()
Array of size 9 is created. But what if there is a requirement to change this
length (size). For Example,
If there is a situation where only 5 elements are needed to be entered in
this array. In this case, the remaining 4 indices are just wasting memory in
this array. So there is a requirement to lessen the length (size) of the array
from 9 to 5.
Take another situation. In this, there is an array of 9 elements with all 9
indices filled. But there is a need to enter 3 more elements in this array. In
this case 3 indices more are required. So the length (size) of the array
needs to be changed from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
There are 4 library functions provided by C defined under <stdlib.h> header
file to facilitate dynamic memory allocation in C programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
1. “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size. It returns
a pointer of type void which can be cast into a pointer of any form.
Syntax:
ptr = (cast-type*) malloc(byte-size)
2. “calloc” or “contiguous allocation” method in C is used to
dynamically allocate the specified number of blocks of memory of the
specified type. It initializes each block with a default value ‘0’.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
3. “free” method in C is used to dynamically de-allocate the memory. The
memory allocated using functions malloc() and calloc() is not de-
allocated on their own. Hence the free() method is used, whenever the
dynamic memory allocation takes place. It helps to reduce wastage of
memory by freeing it.
Syntax:
free(ptr);
4. “realloc” or “re-allocation” method in C is used to dynamically change
the memory allocation of a previously allocated memory. In other words,
if the memory previously allocated with the help of malloc or calloc is
insufficient, realloc can be used to dynamically re-allocate memory.
re-allocation of memory maintains the already present value and new
blocks will be initialized with default garbage value.
Syntax:
ptr = realloc(ptr, newSize);
Difference between malloc and calloc()
The name malloc and calloc() allocates memory dynamically from the heap
segment.
Initialization: malloc() allocates memory block of given size (in bytes) and
returns a pointer to the beginning of the block. malloc() doesn’t initialize the
allocated memory. If we try to access the content of memory block (before
initializing) then we’ll get segmentation fault error(or maybe garbage
values).
Initialization: calloc() allocates the memory and also initializes the
allocated memory block to zero. If we try to access the content of these
blocks then we’ll get 0.
Arguments: malloc() takes single argument where ass calloc() takes two
arguments.