Dynamic Memory Allocation
Hey people in this blog you are going to read about “Dynamic
Memory Allocation”, you need to know before you are using functions like “malloc()”,
“calloc()”, “free()”, etc. in your C/C++ code.
To change or define the size of any data structure during the
runtime is called “Dynamic Memory Allocation”.
To use Dynamic memory allocation we need to use several library
functions
malloc() , calloc()
, free() , realloc(). These operations are including in the
library <stdlib.h> .
1. malloc() function :
The name “malloc” stands for memory
allocation.
SYNTAX : ptr = (CastType *)malloc(size);
The malloc() function reserves a
block of memory of the specified number of bytes. And, it returns a pointer of
void which can be casted into pointers of any form.
2. calloc() function :
The name “calloc” stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory
uninitialized. Whereas, the calloc() function allocates memory and initializes
all bits to zero.
SYNTAX : ptr = (CastType *)calloc(n,elements_size);
Where, n – number of elements
3. free() function :
The dynamically allocated memory created either with
either calloc() or malloc() does not get freed upon themselves. You must explicitly use free() to release the space.
SYNTAX : free(ptr);
4. realloc() function :
The name “realloc”
stands for re-allocation.
“realloc” 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);
It is hard to understand this topic by just reading this
bookish deifinition.
So, let’s just look into some working examples of this, which
might help get insight of this topic in a better way :
1. Declaring an
array of a variable size, using “malloc()“
function.
2. Intializing
an array of variable size with a zero value, using “calloc()” function.
3. Deleting a
memory space occupied by any data structure, using “free()” function.
4. Re-defining
the size of an array, using “realloc()” function.
1.
Declaring an
array of a variable size, using “malloc()“ function.
2.
Intializing
an array of variable size with a zero value, using “calloc()” function.
3.
Deleting a
memory space occupied by any data structure, using “free()” function.
4.
Re-defining
the size of an array, using “realloc()” function.