C Language Common pitfalls Forgetting to copy the return value of realloc into a temporary


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)

/* RIGHT */
if ((tmp = realloc(buf, 16)) != NULL)
    buf = tmp;