]> granicus.if.org Git - xz/commitdiff
xz: Improve handling of failed realloc in xrealloc.
authorLasse Collin <lasse.collin@tukaani.org>
Fri, 28 Sep 2012 17:11:09 +0000 (20:11 +0300)
committerLasse Collin <lasse.collin@tukaani.org>
Fri, 28 Sep 2012 17:11:09 +0000 (20:11 +0300)
Thanks to Jim Meyering.

src/xz/util.c

index 987b4430253959f9c4f24fe6097883a2d47a052d..35850f4c90467ae8308618b158a23d4ec7238cb4 100644 (file)
@@ -26,9 +26,19 @@ xrealloc(void *ptr, size_t size)
 {
        assert(size > 0);
 
+       // Save ptr so that we can free it if realloc fails.
+       // The point is that message_fatal ends up calling stdio functions
+       // which in some libc implementations might allocate memory from
+       // the heap. Freeing ptr improves the chances that there's free
+       // memory for stdio functions if they need it.
+       void *p = ptr;
        ptr = realloc(ptr, size);
-       if (ptr == NULL)
-               message_fatal("%s", strerror(errno));
+
+       if (ptr == NULL) {
+               const int saved_errno = errno;
+               free(p);
+               message_fatal("%s", strerror(saved_errno));
+       }
 
        return ptr;
 }