Dynamic Memory Allocation in C using malloc(), calloc(), free()
GTU Data Structure Practical-2
Introduction to Dynamic Memory Allocation. DMA functions malloc(), calloc(), free() etc.
malloc ()
- #include<stdio.h>
- #include<stdlib.h>
- int main(){
- int *ptr;
- int n,i,sum=0;
- printf("Enter Number of Elements: ");
- scanf("%d",&n);
- ptr=(int*)malloc(n*sizeof(int));
- printf("Enter Elements of Array: ");
- for(i=0;i<n;++i)
- {
- scanf("%d",ptr+i);
- sum+=*(ptr+i);
- }
- printf("Sum=%d",sum);
- free(ptr);
- return 0;
- }
Output
calloc ()
- #include<stdio.h>
- #include<stdlib.h>
- int main(){
- int n,i,*ptr,sum=0;
- printf("Enter Number of Elements: ");
- scanf("%d",&n);
- ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
- printf("Enter elements of array: ");
- for(i=0;i<n;++i)
- {
- scanf("%d",ptr+i);
- sum+=*(ptr+i);
- }
- printf("Sum=%d",sum);
- free(ptr);
- return 0;
- }
Output
free()
The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until the program exit.
Go To :
Home Page:
Practical 1 :
Practical 3 :
Comments
Post a Comment