Forgetting to copy the return value of realloc into a temporary

suggest change

If realloc fails, it returns NULL. If you assign the value of the original buffer to realloc’s return value, and if it returns NULL, then the original buffer (the old pointer) is lost, resulting in a memory leak. The solution is to copy into a temporary pointer, and if that temporary is not NULL, then copy into the real buffer.

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");

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents