ptr2 might be pointing to unallocated memory. It has to do with the way realloc() conducts it's business. Assuming the reallocated area is larger than the currently allocated area, realloc() will:[list=1][*]Attempt to expand current memory area[*]If not enough room to simply expand, allocate room somewhere else, move the contents, and free the original location[*]If room cannot be allocated somewhere else, return NULL and leave the original memory area alone[/list=1] Note that in your code example there is no difference between the amount of memory allocated with malloc and the amount of memory you intend to resize it to (nothing changes, realloc() won't fail).
Consider this:
Code:
void *ptr1, *ptr2;
ptr1 = malloc( 1024 );
ptr2 = ptr1;
ptr1 = realloc( ptr1, 4096 );
If realloc() had to relocate the memory block to accomodate the request, ptr2 now points to unallocated memory. Attempting to free ptr2 in this scenario will raise SIGBUS (which is a bad thing). Remember that pointers are nothing more than variables that hold memory addresses. You can simply check the value of ptr1 to see how realloc() handled the request (nested for clarity):
Code:
if ( ptr1 ) /* realloc did not return NULL */
{
if ( ptr1 != ptr2 ) /* realloc moved the memory block */
{
ptr2 = ptr1; /* make sure ptr2 has the new address */
}
}
else /* realloc failed, and assigned NULL to ptr1 */
{
ptr1 = ptr2; /* reset ptr1 to the allocated memory area */
}
At this point, ptr1 and ptr2 reference the same memory location, regardless of how the realloc() turned out.