Dynamic memory allocation
Dynamic memory allocation
01/22/2019 C.P.Shabariram 1
Static vs Dynamic memory allocation
Static Dynamic
memory is allocated at memory is allocated at
compile time. run time.
01/22/2019 C.P.Shabariram 2
malloc()
• It doesn't initialize memory at execution time,
so it has garbage value initially.
• It returns NULL if memory is not sufficient.
• Syntax:
ptr=(cast-type*)malloc(byte-size)
01/22/2019 C.P.Shabariram 3
Example
#include<stdio.h> printf("Enter elements of array: ");
#include<stdlib.h>
int main(){ for(i=0;i<n;++i)
int n,i,*ptr,sum=0; {
printf("Enter number of elements: scanf("%d",ptr+i);
"); sum+=*(ptr+i);
scanf("%d",&n); }
ptr=(int*)malloc(n*sizeof(int)); printf("Sum=%d",sum);
if(ptr==NULL) free(ptr);
{ return 0;
printf(“Unable to allocate "); }
exit(0);
}
6/25/2022 C.P.Shabariram 4
calloc()
• It initially initialize all bytes to zero.
• It returns NULL if memory is not sufficient.
• Syntax:
• ptr=(cast-type*)calloc(number, byte-size)
01/22/2019 C.P.Shabariram 5
Example
#include<stdio.h> exit(0);
#include<stdlib.h> }
int main(){ printf("Enter elements of array: ")
int n,i,*ptr,sum=0; ;
printf("Enter number of elements: for(i=0;i<n;++i)
"); {
scanf("%d",&n); scanf("%d",ptr+i);
ptr=(int*)calloc(n,sizeof(int)); sum+=*(ptr+i);
//memory allocated using calloc }
if(ptr==NULL) printf("Sum=%d",sum);
{ free(ptr);
printf(“Unable to allocate"); return 0;
}
6/25/2022 C.P.Shabariram 6
realloc() & free()
• realloc()
• it changes the memory size.
• Syntax: ptr=realloc(ptr, new-size)
• free()
• The memory occupied by malloc() or calloc()
functions must be released by calling free()
function.
• Syntax: free(ptr)
01/22/2019 C.P.Shabariram 7
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int)*2);
int I; int *ptr_new;
*ptr = 10;
*(ptr + 1) = 20;
ptr_new = (int *)realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30;
for(i = 0; i < 3; i++)
printf("%d ", *(ptr_new + i));
return 0;
}
6/25/2022 C.P.Shabariram 8