|
|
Realloc() function - Dynamic Allocation
|
Tutorials

Cpp

|
Topic |
How to reallocate memory block using realloc() in C++?
|
|
Explanation |
|
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.
Syntax:
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.
|
| Note |
C++ is one of the most used programming languages in the world. Also known as "C with Classes".
Hope you enjoy this tutorial. Do send your feedback or suggestions on this C++ tutorial. This is a copyright content.
|
|
|
|