Dynamic Memory Allocation
Dynamic Memory Allocation
Dynamic memory
What is Dynamic Memory?
It is the procedure through which the size of a Data structure (like Array) is
changed during the run time.
For example:
If the maximum size of an array is 9, and the entered array is of size 5 then in
this case the remaining 4 indices are just wasting memory to save this memory
we can use dynamic memory during the run time of the code to lessen the size
of the array from 9 to 5.
If the entered array is greater than 9 for example if the size of the entered array
is 12 then we require 3 more indices so the length of the array can be changed
from 9 to 12.
This procedure is known as Dynamic Memory allocation.
There are four predefined library functions to help run dynamic memory
allocation.
The file under which the functions are present is <stdlib.h>.
The four functions are:
1.malloc( )
2.calloc( )
4.realloc( )
3.free( )
1.malloc()
malloc() function is used to allocate single block of requested
memory dynamically. It doesn’t initialize memory at execution time,
so it has garbage value initially. It returns NULL if the requested
memory is not sufficient. If the memory is sufficient it return the
address of the memory in which the data is stored
Syntax:
int n,*ptr;
ptr=(int*)malloc(n*size of(int))
int* the type of data that is stored in the heap memory.
n*size of(int) allocates the memory size.
Ptr stores the base address of the memory in which the data is stored.
2.calloc()
Calloc full form is contagious allocation. Built in function in stdlib.h
library. Used to dynamically allocate multiple blocks of memory and
each block is of the same size.
Malloc allocates single block of memory calloc allocates multiple
blocks of memory