Search code examples
cpointersmemory-managementreturnrealloc

Is it good coding practice to assign the address returned by realloc() to the same pointer?


I saw some code related to realloc() on some sites as below.

int *p = (int *)malloc(sizeof(int) * 10);
p = (int *)realloc(p, 100);

But as the standard says, if realloc fails, the original block is left untouched and it returns NULL.

So if realloc fails, from above example, we will lose the ability to free p. Can any one please let me know is it good coding practice to assign the address returned by realloc() to the same pointer?


Solution

  • You are correct that directly assigning the return value of realloc to your only copy of the original pointer is a bad practice. Not only do you lose the ability to free the memory if realloc failed (I would call this the lesser issue); you also lose the data that your pointer pointed to.

    For some programs this may not matter (e.g. if you're just going to terminate and abort the entire operation on allocation failures, which may or may not be acceptable practice, and which is a whole topic in itself) but in general you need to first store the result of realloc to a separate temp variable, and only overwrite the original pointer variable after you check that it succeeded.