Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - If realloc is used is free necessary?

Tags:

c

pointers

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;
like image 701
Cory Avatar asked Mar 24 '11 23:03

Cory


People also ask

Do you need to use free with realloc?

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.

Do you need to free before realloc C?

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.

Do I need to free old pointer after realloc?

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.

Do you need to free malloc in C?

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.


1 Answers

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);
like image 177
Scorpions4ever Avatar answered Sep 17 '22 20:09

Scorpions4ever