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
ptr -- A pointer to a memory block previously allocated with malloc, calloc, or realloc. If it is a null pointer, a new memory block is allocated, and a pointer to it is returned.
size -- The new size for the memory block, in bytes. If it is 0 and ptr points to an existing memory block, the memory block pointed to by ptr is deallocated, and a null pointer is returned.
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