Realloc() function - Dynamic Allocation

How to reallocate memory block using realloc() in C++?


Realloc() function, dynamic allocation, changes the size of the previously allocated memory pointed by "ptr" of the specific "size". The function returns a pointer to the memory since "realloc()" will move the memory to change the size. If the "size" is zero the memory pointed is freed. If there is no enough memory to reallocate, the pointer returns "NULL", and original memory will remain the same.


void *realloc(void *ptr, size_t size);

Example :

#include <iostream.h>
#include <stdlib.h>
void main()
char *ptr;
ptr = (char*)malloc(6);
strcpy(ptr, "HAPPY");
cout << "Initial content is:: " << ptr << endl;
realloc(ptr, 10);
strcpy(ptr, "HAPPYDAYS");
cout<< "Content after Realloc is:: " << ptr << endl;

Result :

Initial content is::HAPPY
Content after Realloc is::HAPPYDAYS

In the above example, first the memory block is allocated, then it is reallocated to more bytes using the realloc(). Thus to reallocate memory block this function can be used. This is the realloc() function of dynamic allocation.

C++ Tutorial

Ask Questions

Ask Question