After ptr1 = realloc(ptr2, 3 * sizeof(int));
ptr2 is invalid and should not be used. You need to free ptr1
only. In some cases the return value of realloc
will be the same value you passed in though.
You can safely consider ptr1=realloc(ptr2, ...
as equivalent to this:
ptr1 = malloc(...);
memcpy(ptr1, ptr2, ...);
free(ptr2);
This is what happens in most cases, unless the new size still fits in the old memory block - then realloc could return the original memory block.
As other allocation functions, realloc
returns NULL if it fails - you may want to check for that.