C++ cstdlib realloc function


The C++ <cstdlib> realloc deallocate the old storage and returns a pointer to the new storage allocated.The declaration of the function is shown below.

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

Parameters:
mem -Pointer to the previous memory and also whose memory is also to be reallocate.Simply the memory pointed to by ‘mem’ will be enlarged.

size -The new size of the memory to be reallocated.

Return type
void*-‘NULL’ is returned if allocation fails or the pointer ‘mem’ is returned:the pointer to the reallocated memory.

Some points to note:

i) Calling ‘realloc’ to allocate memory larger than the previously allocated size preserve the content in the previous memory.The content in the new extended memory is indeterminate.

ii)If the pointer=the first argument- passed points to ‘nullptr’ or is ‘NULL’ type then the ‘realloc’ function behave like the ‘malloc’ function.

iii) If the pointer passed does not match the earlier pointer,means the pointer points to memory which is not allocated by ‘calloc’ , ‘malloc’ or ‘realloc’ call then the behavior is undefined.And also if the memory pointed by the pointer has be deallocated the behavior is undefined.

iv) If the size passed is smaller than the previous memory allocated size the result is undefined.

v) If the memory cannot be allocated then the old object is not deallocated and the content is also preserve.

Link : C++ cstdlib malloc

Code example

char st[]=”Malloc” ;
size_t sz=10 ;

char *mem=(char*)malloc( sz );

memcpy( mem , st , strlen(st) ); ///copies the content of st to ‘mem’

cout<< mem << endl ;

sz+=sz ; ///sz become 20

mem=(char*)realloc( mem , sz ); ///the memory pointed by ‘mem’ size is increased to 20 bytes

cout<< mem ; //checking if the previous content is preserve

free(mem) ; ///do not forget

Output,

Malloc
Malloc

As you can see the previous content stored in ‘mem’ is preserve after ‘realloc’ is called.





A more exhaustive code example is given below.

Code example:In this example we will try to enlarge the size of the memory and also append new content to the content of the previous storage.

#include <iostream>
#include <cstdlib>
#include <cstring> ///strlen function is include here

using namespace std ;

int main( )
{
char st[]=”new old and happy sad” ,
  st1[]=” Due date” ;

size_t sz=25 ;

char *cmem=(char*)malloc( sz ) ;

memcpy( cmem , st , strlen(st)+1 ); //copies content of ‘st’ to ‘cmem’

cout<< cmem << endl ; //outputting the content of ‘cmem’

sz+=10;

cmem=(char*)realloc( cmem , sz );

memcpy( cmem+strlen(st) , st1 , strlen(st)+1 ); //Append content of ‘st1’ to the content found in ‘cmem’

cout<< cmem ; //outputting the content of ‘cmem’

free(cmem);

cin.get( );
return 0;
}

Output,

new old and happy
new old and happy sad Due date

Link : C++ cstdlib free

You should prefer the C++ way of dynamic memory allocation instead of C style dynamic memory allocation for many reasons.

Link : C++ dynamic memory allocation