C - Use realloc() function to re-allocate memory

Introduction

realloc() function has the following format:

p = realloc(buffer,size); 
  • buffer is an existing storage area, created by the malloc() function.
  • size is the new buffer size based upon however many units you need of a specific variable type.

Upon success, realloc() returns a pointer to buffer; otherwise, NULL is returned.

In the following code, the realloc() function resizes an already created buffer to a new value.

Demo

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() /*from w  w  w.j  ava 2  s . co m*/
{ 
   char *input; 
   int len; 

   input = (char *)malloc(sizeof(char)*1024); 
   if(input==NULL) 
   { 
       puts("Unable to allocate buffer! Oh no!"); 
       exit(1); 
   } 
   puts("Type something long and boring:"); 
   fgets(input,1023,stdin); 
   len = strlen(input); 
   if(realloc(input,sizeof(char)*(len+1))==NULL) 
   { 
       puts("Unable to reallocate buffer!"); 
       exit(1); 
   } 
   puts("Memory reallocated."); 
   puts("You wrote:"); 
   printf("\"%s\"\n",input); 

   return(0); 
}

Result

Related Topic