Any dynamically located memory, remains allocated till the time that program is available. To deallocate the memory we need to explicitly deallocate the memory by using function free()
Example malloc,realloc,free :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int n;
printf(“Enter size of array”);
scanf(“%d”, &n);
int *a = (int)malloc(n*sizeOf(int)); //dynamically allocated array
//if we donot initialize the values in the array, then by default the malloc will assign garbage values in the block
of memory
//so if we comment the below for loop then it will print garbage values
for(int i = 0; i < n; i++)
{
a[i]=i+1;//assigning values as 1,2,3..n;
}
//if we use free() function below, to free the memory space then free() function will erase all the data from
memory.
//Free(a);// so better not to use free() here
//now this below for loop will print garbage values because the free() has removed all data from memory.
//To resize the memory block: we have memory block to store n elements in an array, and we want to double the size
of array or want to reduce the size, so for this we can use realloc().
int *b = (int )realloc(a,2*n*sizeof(int));//this will allocate double the size of previous block.
//after realloc(), it will create new memory block of size 2n and copy the values of previous block of memory values
into the new memory block b.
//so previous values for n =2,were a[0]=1 and a[1]=2, then after realloc, the block of memory will be 2*n=2*2=4
//so if we print the values that is there in the new block b as
for(int i = 0; i < n; i++)
{
printf(“%d ”,b[i]);
//n=2,so new size of memory block is 2*2=4,this will print values as “1 2 garbagevalue1 garbagevalue2”.
//since 1 and 2 are values of previous block a, so they are copied in the new block b
//and garbage values are printed in the new block of memory because till now no values are assigned in the new block
of memory
}
for(int i = 0; i < n; i++)
{
printf(“%d ”,a[i]); //this will print values as 1 2 3...n
}
//this will deallocate after the block of memory has been used , so that it can be reused.
free();
}
Example for calloc():
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int n;
printf(“enter size of array”);
scanf(“%d”, &n);
int *a = (int)calloc(n*sizeOf(int)); //dynamically allocated array
//if we do not initialize the values in the array then by default the calloc will assign zeros in the block of
memory.
//so if we comment the below for loop then it will print all values as zero on the console
//and if we assign values by using the below for loop , then it print all the values that are assigned in the block
of memory
for(int i = 0; i < n; i++)
{
a[i]=i+1;//assigning values as 1,2,3...n;
}
for(int i = 0; i < n; i++)
{
printf(“%d ”,a[i]); //this will print values as 1 2 3...n
}
}
No comments:
Post a Comment