Dynamic Memory Allocation in C

Dynamic Memory Allocation in C


We know the memory allocation is classified into Static and Dynamic allocation.In brief Static memory is allocated before execution of any program. Here let we discuss about dynamic memory allocation in detail.

Dynamic memory allocation simply means allocation of memory at run time. Dynamic memory is some time more preferable when we are not able to decide the exact size. Suppose in the case of array if the sufficient size is not define then that causes program failure occur. For overcoming such type of failure dynamic memory is needed.

Dynamic memory have following advantages such as:

  • For Reduce the wastage of memory , we can easily understand by taking an example suppose if we use any array of size 100 in our program and static memory allocation is used for allocation memory.At the time of execution if we are using only 50% of allocated memory than the rest of 50% is waste.That means allocated memory is not properly utilised. But in the place of static,if we use dynamic memory allocation then we overcome such a wastage because in dynamic memory is allocated at runtime or execution time.
  • Provide Flexibility in change the size of array.In any static memory allocation scheme changing the size of array in not possible because it is fix but not in dynamic memory allocation scheme.

For managing such a memory management scheme at runtime , C language provide four library functions such as:

  1. Malloc()
  2. Calloc()
  3. Realloc()
  4. Free()

These functions are declared in <stdlib.h> and <alloc.h> header files in C library.These functions are helpful for building complex programs such as creating a linked list.


Let we know about the memory allocation process:


For understand memory allocation process we must know about the storage structure of C.The storage is divided into many regions and each regions can store different things in it such as Local variables,Global variables,Program instructions etc.Let we discuss about those regions such as:

  • Stack : This region is responsible to store local variables.
  • Heap : This region is responsible to store those variable which is dynamic allocated during execution.Here the size of heap keeps changing when program is executed due to creation and destruction of variables that are local in blocks of functions.
  • Permanent Storage area : This region is responsible to store program instructions and global/static variables.

Let we discuss about library function in detail:

Malloc()

Malloc stands for memory allocation. Malloc function is used to allocate a single block of memory.It reserve the space in memory according to the size variable that linked with a pointer.This pointer contain the starting address of memory.The memory allocation is in continuous manner.Here allocated space is not filled with zero but it returns 0 or NULL if the space in the heap is not sufficient to satisfy the request.So we must check the memory allocation before using memory pointer.

Syntax:

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

Example 1:

Copy Code
#include <stdio.h>
#include <stdlib.h>

void main()
{
   void * ptr;
   ptr=malloc(4);
   if(ptr==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated\n");
   }
}

In the above example void *ptr means pointer points to any datatype we are not specify any datatype.Generally malloc() returns NULL pointer it does not point any datatype.If we want that malloc() point any datatype than we must specify the datatype such as (cast-type*)malloc(any unsigned integer);,Here cast-type is data type where we cast one type to another such as (float)x where x is integer so integer is converted into float.

Example 2:

Copy Code
#include <stdio.h>
#include <stdlib.h>

void main()
{
   int * ptr;
   ptr=(int*)malloc(4);
   if(ptr==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated\n");
   }
}

In above example if we don't know how many bytes the datatype takes than we can use sizeof () to find the length or number of byte will consume by datatype.

Example 3:

Copy Code
#include <stdio.h>
#include <stdlib.h>

void main()
{
   int *ptr;
   ptr=(int*)malloc(sizeof(int));
   if(ptr==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated\n");
   }
}

Calloc()

Calloc stands for calculated allocation.It is used to allocate memory location for derived data type at run time.Derived data type such as arrays and structures. Calloc can allocate multiple block of memory space of same size.It fill allocated memory space with 0 automatically.It return starting address of memory if allocation is successful and return 0 or NULL if allocation fails.

Syntax:

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

Example :


Copy Code
#include <stdio.h>
#include <stdlib.h>

void main()
{
    int n;
   char *ptrc;
   ptrc=(char*)calloc(n,sizeof(char));
   if(ptrc==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated\n");
   }
}

Realloc()

It is used to modify memory space that allocated previously.That means we can increase or decrease the block size of heap memory according to required size.During this process we preserve the starting address and data of block.

Syntax:

ptr=realloc(ptr,ptr-size);

Example :

Copy Code
#include <stdio.h>
#include <stdlib.h>
void main()
{
   int *ptr;
   ptr=(int*)malloc(50);
   if(ptr==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated by malloc()\n");
   }
   //After fill the memory of 50 byte we will extend upto 100 more byte.
   ptr=(int*)realloc(ptr,100);
}

Free()

This function is used to free the memory allocated by alloc(),malloc(),calloc() or realloc() and the space is available in the heap for further activity.It is recommended that before termination program execution you must free memory used by program.

Syntax:

free(ptr);


Examples 

Program 1 :


Copy Code
#include<stdlib.h>
#include<stdio.h>
void main()
{
    int *A,*B;
    int n;
    printf("Enter size of array:");
    scanf("%d",&n);
    if(A==NULL)
    {
        printf("Memory is full!");
    }
   
    A=(int*)calloc(n,sizeof(int));
   
    for(int i=0;i<n;i++)
    {
        A[i]=i+1;
    }
     printf("\nA:");
    for(int i=0;i<n;i++)
    {
        printf("%d\t",A[i]);
    }
    B=(int*)realloc(A,10*sizeof(int));
   
    printf("\nB:");
   
    for(int i=0;i<n;i++)
    {
        printf("%d\t",B[i]);
    }
   
}

Program 2 :

Copy Code
#include<stdlib.h>
#include<stdio.h>
void main()
{
    int *A,*B;
    int n;
    printf("Enter size of array:");
    scanf("%d",&n);
    if(A==NULL)
    {
        printf("Memory is full!");
    }
   
    A=(int*)malloc(sizeof(int));
   
    for(int i=0;i<n;i++)
    {
        A[i]=i+1;
    }
     printf("\nA:");
    for(int i=0;i<n;i++)
    {
        printf("%d\t",A[i]);
    }
    B=(int*)realloc(A,10*sizeof(int));
   
    printf("\nB:");
   
    for(int i=0;i<n;i++)
    {
        printf("%d\t",B[i]);
    }    
}

Know more about pointers


No comments:

Post a Comment