Dynamic Memory Allocation In C Language

aimtocode

Dynamic Memory Allocation

Dynamic memory allocation is a technique in which programs determine as they are running where to store some information. You need dynamic allocation when the amount of memory you need, or how long you continue to need it, depends on factors that are not known before the program runs.

malloc() function in C

  • The malloc() function allocates single block of requested memory.
  • It doesn't initialize memory at execution time, so it has garbage value initially.

Syntax:

  
  ptr=(cast-type*)malloc(byte-size)


Example:

 #include<stdio.h>
 #include<stdlib.h>
 int main()
 {
    int i,length,sum=0;
    printf(" Enter the count of numbers:");
    scanf("%d", &length);
    int *p;
    p=(int*) malloc((sizeof(int)*length);
    for(i=0; i<length;i++)
    {
        printf("Enter a number :");
        scanf("%d",p+i);
    }
    for(i=0; i<length;i++)
    {
        sum=sum+*(p+i);
    }
    return 0;
 }

After using malloc() function memory must be restored using de-allocation. The memory has to be de-allocated to efficiently use the memory space. So, to free up the memory allocated, use free() function. Then that freed space is ready to use again

Example:

 #include<stdio.h>
 #include<stdlib.h>
 int main()
 {
    int i,length,sum=0;
    printf(" Enter the count of numbers:");
    scanf("%d", &length);
    int *p;
    p=(int*) malloc((sizeof(int)*length);
    for(i=0; i<length;i++)
    {
        printf("Enter a number :");
        scanf("%d",p+i);
    }
    for(i=0; i<length;i++)
    {
        sum=sum+*(p+i);
    }
    return 0;
 }

calloc() function in C

  • The calloc() function allocates multiple block of requested memory.
  • It initially initialize all bytes to zero.
  • It returns NULL if memory is not sufficient.

Syntax:


 ptr=(cast-type*)calloc(number, byte-size)  


Example:

 #include<stdio.h>
 #include<string.h>
 #include<stdlib.h>
 int main()
 {
    int length,i;
    int *ptr;
    printf("Enter count of number:");
    scanf("%d",&length);
    ptr=(int*)calloc(length,sizeof(int));
    if(ptr==NULL)
    {
        printf("Cannot allocate memory");
        exit(1);
    }
    for(i=0;i<length;i++)
    {
        printf("Enter a number %d: ",i);
        scanf("%d",&ptr[i]);
    }
    for(i=0;i<length;i++)
    {
        printf("Enter a number %d: ",i);
        scanf("%d",ptr[i]);
    }
    return 0;
 }
aimtocode