Forgetting to copy the return value of realloc into a temporary
suggest changeIf realloc fails, it returns a null pointer and leaves the original allocation unchanged. If you overwrite the only pointer to that allocation with the null return value, the allocation is leaked. Store the result in a temporary pointer and replace the original only when the temporary is not null.
char *buf, *tmp;
buf = malloc(...);
...
/* WRONG */
if ((buf = realloc(buf, 16)) == NULL)
perror("realloc");
/* RIGHT */
if ((tmp = realloc(buf, 16)) != NULL)
buf = tmp;
else
perror("realloc");
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents