If memory is allocated dynamically using new then can we expand the allocated memory using realloc( )?

Yes, we can! This can be explained with the help of following example:

#include <iostream.h>
#include <malloc.h> 
void main( )

       int *p = new int[5] ; 
       p[1] = 3 ; 
       p = ( int * ) realloc ( p, sizeof ( int ) * 5 ) ; 
       cout << p[1] ; 

The realloc( ) function expands the existing allocated memory if it finds enough contiguous memory locations that are required. If enough contiguous memory blocks are not available then the new memory block is allocated. The existing data is copied and the original memory block is freed.

No comments:

Post a Comment