Forgetting to copy the return value of realloc into a temporary
suggest changeIf 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");
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents