DS | Practical-2 | Dynamic Memory Allocation in C using malloc(), calloc(), free()


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 ()

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. int main(){
  4. int *ptr;
  5. int n,i,sum=0;
  6. printf("Enter Number of Elements: ");
  7. scanf("%d",&n);
  8. ptr=(int*)malloc(n*sizeof(int));
  9. printf("Enter Elements of Array: ");
  10. for(i=0;i<n;++i)
  11. {
  12. scanf("%d",ptr+i);
  13. sum+=*(ptr+i);
  14. }
  15. printf("Sum=%d",sum);
  16. free(ptr);
  17. return 0;
  18. }

Output

calloc ()

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. int main(){
  4. int n,i,*ptr,sum=0;
  5. printf("Enter Number of Elements: ");
  6. scanf("%d",&n);
  7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
  8. printf("Enter elements of array: ");
  9. for(i=0;i<n;++i)
  10. {
  11. scanf("%d",ptr+i);
  12. sum+=*(ptr+i);
  13. }
  14. printf("Sum=%d",sum);
  15. free(ptr);
  16. return 0;
  17. }

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