Dynamic Memory Allocation in C


 Dynamic Memory Allocation 

Dynamic Memory Allocation means Memory allocated at runtime.

Dynamic Memory Allocation can be defined as a procedure in which the size of data structure (like array)is changed during the runtime.

C programming provides some functions to achieve the Dynamic Memory allocation.

There are 4 library functions provided by C defined under the <stdlib.h> header file.The functions are: 

1. malloc()
2. calloc()
3. realloc()
4. free()

1. malloc() function 

The malloc means memory allocation method in C is used to allocate a single large block of memory dynamically with the specified size in bytes. malloc() functions returns a generic void pointer which can be cast into a pointer of any form.

It has initialized each block with the default garbage value initially.The memory will initialize in the Heap section.

Generally we use malloc function to locate the memory for structures.

Syntax 

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

Example 

ptr= (int*) malloc (20*sizeof(int));

This statement will allocate 80 bytes ( since the size of int is 4 bytes) of memory.and the pointer ptr holds the address of the first byte in allocated memory  (base address).

It returns NULL if memory is not allocated or not sufficient.

Program Example

#include<stdlib.h>
#include<stdio.h>
int main()
{
    int n,i,*ptr,sum=0;
    printf("Enter number of elements:");
    scanf("%d",&n);
    ptr=(int*) malloc (n*sizeof(int));
    if(ptr==NULL)
    {
        printf("Sorry unable to allocate memory");
        exit(0);
    }
    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

Enter number of elements : 3

Enter elements of array : 10 11 12

sum=33


2. calloc() function

calloc means contiguous allocation method in C is used to dynamically allocate the specified number of blocks of memory of the specified type.
 
this method is very much similar to malloc() but has some differences are given below :-

  • It has two parameters or arguments as compare to malloc() function which has only one parameter.
  • calloc() method allocate the  multiple blocks of specified size.
  • It initializes each block with a default value '0'.

Syntax

ptr=(cast-type*) calloc(n, element-size);

Here, n is the number of elements and element-size is the size of each block.

Example

ptr=(float*)calloc(25,sizeof(float));

This statement allocates contiguous blocks in memory for 25 elements each with the size of the float.

If space is insufficient, allocation fails and returns a NULL pointer.

Program Example

# include<stdio.h>
#include<stdlib.h>
int main()
{
    int *ptr, n, i;
    printf("Enter the number of elements in the array:");
    sacnf("%d", &n);
    ptr=(int*)calloc(n,sizeof(int));
    if(ptr==NULL)
    {
        printf("memory is not allocated:\n");
        exit(0);
     }
    else
    {
        printf("Memory successfully allocated using calloc:\n");
        for(i=0;i<n;++i)
        {
            ptr[i]=i+1;
         }
         printf("The elements of the array are:");
         for(i=0;i<n;++i)
         {
                printf("%d",ptr[i]);
          }
       }
    return 0;
}

Output

Enter the number of elements in the array : 5

Memory successfully allocated using calloc

The elements of the array are : 2 5 4 6 8 

3. realloc() function 

realloc means Re-allocation method in C is used to dynamically change the memory allocation of a previously allocated memory. We can say if the memory previously allocated with the help of malloc() or calloc() function is insufficient, realloc() function can be used to re-allocated the memory dynamically.

re-allocation of memory maintains the already present value and new blocks will be initialized with the default value.

Syntax 

ptr=realloc(ptr, newsize);

where ptr is reallocated with the new size "newsize".

Example 

int *ptr=(int*)malloc(5*sizeof(int));

This statement will allocate a single memory block of 20 bytes(if the integer size will be 4 bytes) and allocated to ptr.

If we want to change the memory allocated to ptr then we can use realloc() function to change the allocated memory dynamically.

ptr=realloc(ptr, 10*sizeof(int));

By using this statement the size of ptr is changed from 20 bytes to 40 bytes dynamically and allocated to ptr.


Program Example

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int *ptr, n, i;
    printf("Enter the number of elements in the array:");
    scanf("%d", &n);
    ptr=(int*)calloc(n,sizeof(int));
    if(ptr==NULL) 
    {
        printf("Memory not allocated\n");
        exit(0);
    }
    else
    {
        printf("Memory successfully allocated\n");
        for(i=0;i<n;++i)
        {
            ptr[i]=i+1;
        }
        printf("The elements of the array are:");
        for(i=0;i<n;++i);
        {
            printf("%d",ptr[i]);
        }
        printf("Enter the new size :");
        scanf("%d", &n);
        ptr=realloc(ptr, n*sizeof(int));
        printf("Memory successfully re=allocated\n");
        for(i=0;i<n;++i)
            {
                ptr[i]=-i+1;
            }
            printf("The elements of the new array are:");
            for(i=0;i<n;++i)
            {
                printf("%d", ptr[i]);
            }
            free(ptr);
     }
        return 0;
}

4. free() function

The free() method in C programming is used to dynamically de-allocate the memory which is allocated by the calloc() or malloc() method. It helps to reduce the wastage of memory.

The memory occupied by malloc() or calloc() functions must be released by calling free() function. If we do not free the memory which is already allocated than it will consume memory until program exit.


Syntax

free(ptr);

Note :  If we will try to access the memory location which has been de-allocated by using free() function then it will show you an undefined behavior.




              







No comments:

Post a Comment