When using realloc is the memory automatically freed? Or is it necessary to use free with realloc? Which of the following is correct?
//Situation A
ptr1 = realloc(ptr1, 3 * sizeof(int));
//Situation B
ptr1 = realloc(ptr2, 3 * sizeof(int));
free(ptr1);
ptr1 = ptr2;
In short, no. Once you call realloc() , you do not have to free() the memory addressed by pointer passed to realloc() - you have to free() the memory addressed by the pointer realloc() returns.
The specific usefulness of realloc is that you don't need to free before using it: it exists to grow memory that has already been allocated. So it is not required and would be uncommon.
When reallocating the old pointer is invalidated and does not need to be freed manually. Only the last pointer after reallocating needs to be freed manually. The only exception to this is if realloc returns a null pointer. Only then is the old pointer still valid and still needs to be freed manually.
But the memory allocation using malloc() is not de-allocated on its own. So, “free()” method is used to de-allocate the memory. But the free() method is not compulsory to use.
Neither is correct. realloc() can return a pointer to newly allocated memory or NULL on error. What you should do is check the return value:
ptr1 = realloc(ptr2, 3 * sizeof(int));
if (!ptr1) {
/* Do something here to handle the failure */
/* ptr2 is still pointing to allocated memory, so you may need to free(ptr2) here */
}
/* Success! ptr1 is now pointing to allocated memory and ptr2 was deallocated already */
free(ptr1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With