The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur.
The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer
Realloc () function used to expands the existing allocated memory if it finds enough continus memory location that are required if enough continus memory are not available new memory of block is allocated.The existing data is copied and the origibnal memory block is freed. for example::
int *p new int[5]; p[1] 3; p (int*) realloc (p sizeof(int) *5); cout<<p[1];
I think the example mentioned in your answer wont double the size of memory pointed by the ptest. Instead it creates equal sized one and copies all the content to new memory. To get the expected result i believe the code should look like this.
>> realloc(ptest sizeof(test)*2); // to double the size of the mem.
free() deallocates memoru allocated by maaloc calloc or realloc. Whenevr there is a need to allocate extra memory we can use realloc. realloc means free+malloc once more. following example may explain this behaviour.
Mitra as you mentioned that realloc will delete the existing memory and allocate the new memory . I tried it on solaris and following is found :
1. If the new size allocated is less than the existing memory size then realloc will allocate existing memory size. In other words will leave it. 2. If the new size allocated is more than the existing memory size then realloc will allocate new memory size.
In either of these two cases the realloc will not delete the contents.
What you said is partially correct. Realloc when trying to allocate required memory size and if it could not find a continuous memory then it will allocate new memory which will automatically give garbage as it now points to new memory.
free() - releases the memory of the pointer passed as parameter to the OS/application consumption. Using the pointer after free() will result in undefinded results
realloc() - used to resize the memory held by the pointer to the number of bytes specificed. If the new size is larger than current size new memory is allocated. If it is less the remaining (additional) bytes are released to general OS/application consumption.