dynamic Memory Allocation
dynamic Memory Allocation
As it can be seen that the length (size) of the array above made is 9. 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.
1. malloc()
2. calloc()
3. free()
4. realloc()
C malloc() method
The “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. It doesn’t Initialize memory at execution time so that
it has initialized each block with the default garbage value initially.
Syntax:
Syntax:
Syntax:
free(ptr);
realloc() method
“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 the default garbage value.
Syntax: