realloc
may return either the same input address or a different address. If it returns a different address then it shall internally de-allocate/free the input memory and moving that content into an another location and returns that new address.
Please consider the following case.
new_ptr = realloc (2000, 10000) // Lets assume the input address is 2000
// Lets assume the new_ptr address is 3000
So, internally realloc
shall free the memory where pointer points to 2000 and move those data into a new location 3000 and return the 3000 address.
Now the address 2000 is points to invalid. Hence it is not assigned to NULL by realloc
API.
Now, passing that invalid address to realloc function. In real time there may be changes that realloc may get the invalid input address.
new_ptr = realloc(2000, 10000)
This 2000 address is invalid since it is already freed by previous realloc
. Now the program crashes.
Can I resolve this issue by doing the following way.
if (new_ptr != old_ptr ) {
old_ptr = NULL;
}
Since the old_ptr is invalid. I shall assign it to NULL. Please confirm me the correction.