C realloc()

The realloc() function is defined in the stdlib.h header file. It helps to resize the memory block pointed by the pointer which is previously allocated using the malloc() or calloc() function.

void *realloc(void *ptr, size_t size); #where size should be a bytes


realloc() Parameters: 

The realloc() function takes two parameters. If ptr is is NULL, a new block is allocated and a pointer to it is returned.

Parameter Description Required / Optional
ptr  pointer to a memory block previously allocated and need to be reallocated Required
size the new size for the memory block, in bytes Required

realloc() Return Value

 If size is 0 and ptr points to an existing memory block, the memory block pointed by ptr is deallocated and a NULL pointer is returned.

Input Return Value
success pointer to memory
fails NULL

Examples of realloc() 

Example 1: Working of realloc() function in C?

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

int main()
   char *s;

   /*memory allocation */
   s = (char *) malloc(12);
   strcpy(s, "programming");
   printf("String = %s,  Address = %u\n", s, s);

   /* Reallocating memory */
   s = (char *) realloc(s, 20);
   strcat(s, ".com");
   printf("String = %s,  Address = %u\n", s, s);



String = programming, Address = 355090448
String = programming.com, Address = 355090448

Example 2: How realloc() works in C?

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

int main (){
  int k, * p, t = 0;
        p = malloc(200);
        if (p == NULL) {
            printf("Error! memory not allocated.");
        p = realloc(p,400);
    if(p != NULL)
           printf("Memory created successfully\n");
    return 0;


Memory created successfully