Memory Allocation
Already we, know about the Static allocation and Automatic
allocation.
Now a third important kind of memory allocation is known as
dynamic allocation.
Dynamic Memory Allocation:
The process of allocation memory to the variables during execution
of the program or at run time is known as dynamic memory
allocation.
1. malloc( ) :
malloc( ) function is used to allocate space in memory during the
execution of the program.
It does not initialize the memory allocated during execution.
It carries garbage value.
It returns null pointer if it couldn’t be able to allocate requested
amount of memory.
2. calloc( ) :
calloc( ) function is also like malloc( ), but calloc( ) initializes the
allocated memory to
zero.
3. realloc( ) :
realloc ( ) function modifies the allocated memory size by malloc( )
and calloc( ) functions to new size.
If enough space doesn’t exist in memory of current block to extend,
new block is allocated for the fullsize of reallocation, then copies the
existing data to new block and then frees the old block.
4. free ( ) :
free ( ) function frees the allocated memory by malloc ( ) and calloc ( )
functions and returns the memory to the system.
Example:
Program to allocate memory for an array dynamically, store and
access its values,
Example of calloc and malloc
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int *arr, i, n;
printf(“Enter the size of the array”);
scanf(“%d”,&n);
arr = (int *) malloc(n * sizeof(int));
if(arr == NULL)
{
printf(“\n Memory allocation Failed”);
exit (0);
}
for(i=0; i<n; i++)
{
printf(“Enter the value %d of the array”, i);
scanf(“%d”,&arr[i]);
}
printf(“\n Elements of the array”);
for(i=0;i<n;i++)
printf(“%d ”,arr[i]);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int *arr, i, n;
printf(“Enter the size of the array”);
scanf(“%d”,&n);
arr = (int *) calloc(n, sizeof(int));
if (arr == NULL)
exit(1);
printf(“Enter %d elements into the array”, n);
for(i=0; i<n; i++)
scanf(“%d”,&arr[i]);
printf(“\n Elements of the array”);
for(i=0;i<n;i++)
printf(“%d ”,arr[i]);
free(arr);
return 0;
}