Course Content
Data Structure Algorithms with C Language

realloc()

it is used to extend or reduce previously allocated memory using malloc or calloc functions.  It won’t actually add or remove new blocks.  It will just create a parallel memory and copy old data into it.  Newly allocated blocks of un-initialised.

 

syntax:

void *realloc(void *ptr,n);

 

where

ptr – pointer of previously allocated memory

n – size of new memory required

 

Eg:

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

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

 

where

ptr is the starting byte of existing memory

n is new memory blocks we want

 

//Example program

#include<stdio.h>

 

void main()

{

    int i;

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

 

    if(ptr==NULL)

    {

        printf(“Memory not available”);

        exit(1);

    }

    printf(“Enter the two numbers:n”);

 

    for(i=0;i<2;i++)

    {

        scanf(“%d”,ptr+i);

    }

 

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

    if(ptr==NULL)

    {

        printf(“Memory not available”);

        exit(1);

    }

    printf(“Enter 2 more integers:n”);

    for(i=2;i<4;i++)

    {

        scanf(“%d”,ptr+i);

    }

 

    for(i=0;i<4;i++)

    {

        printf(“%d “,*(ptr+i));

    }

}

 

You cannot copy content of this page