realloc() function has the following format:
p = realloc(buffer,size);
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.
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() /*from w w w .j ava2 s . c o 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); }