Easy Tutorial
❮ C Examples Copy Array C Examples Average Arrays ❯

C Library Function - realloc()

C Standard Library - <stdlib.h>

Description

The C library function void *realloc(void *ptr, size_t size) attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.

Declaration

Here is the declaration for the realloc() function.

void *realloc(void *ptr, size_t size)

Parameters

Return Value

The function returns a pointer to the reallocated memory block. If the request fails, it returns NULL.

Example

The following example demonstrates the use of the realloc() function.

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

int main()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialpro");
   printf("String = %s,  Address = %p\n", str, str);

   /* Reallocate memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %p\n", str, str);

   free(str);

   return(0);
}

Let's compile and run the above program, which will produce the following result:

String = tutorialpro,  Address = 0x7fa2f8c02b10
String = tutorialpro.org,  Address = 0x7fa2f8c02b10

C Standard Library - <stdlib.h>

❮ C Examples Copy Array C Examples Average Arrays ❯