[PATCH 2/5] Fix the handling of realloc failures.

David Shea dshea at redhat.com
Fri Jan 31 15:23:23 UTC 2014


Assigning the result of realloc directly to the varaiable being resized
can cause a memory leak, because the result of realloc can be NULL. Our
code probably still can't deal with malloc failures, and I'm not sure if
malloc/realloc can ever return NULL at all these days, but this fix will
keep us from being haunted by the ghosts of all of our intro to CS
instructors.
---
 pyanaconda/isys/devices.c | 17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)

diff --git a/pyanaconda/isys/devices.c b/pyanaconda/isys/devices.c
index 36c2ece..1f7a6c1 100644
--- a/pyanaconda/isys/devices.c
+++ b/pyanaconda/isys/devices.c
@@ -51,6 +51,7 @@
 
 struct device **getDevices(enum deviceType type) {
     struct device **ret = NULL;
+    struct device **tmpret;
     struct device *new;
     int numdevices = 0;
 
@@ -133,7 +134,13 @@ struct device **getDevices(enum deviceType type) {
             if (caps & GENHD_FL_REMOVABLE) {
                 new->priv.removable = 1;
             }
-            ret = realloc(ret, (numdevices+2) * sizeof(struct device));
+            tmpret = realloc(ret, (numdevices+2) * sizeof(struct device));
+            if (NULL == tmpret)
+            {
+                free(ret);
+                return NULL;
+            }
+            ret = tmpret;
             ret[numdevices] = new;
             ret[numdevices+1] = NULL;
             numdevices++;
@@ -213,7 +220,13 @@ storagedone:
                 }
             }
 
-            ret = realloc(ret, (numdevices+2) * sizeof(struct device));
+            tmpret = realloc(ret, (numdevices+2) * sizeof(struct device));
+            if (NULL == tmpret)
+            {
+                free(ret);
+                return NULL;
+            }
+            ret = tmpret;
             ret[numdevices] = new;
             ret[numdevices+1] = NULL;
             numdevices++;
-- 
1.8.5.3



More information about the anaconda-patches mailing list