[Libguestfs] [PATCH 1/2] Check for failures in memory allocations

Pino Toscano ptoscano at redhat.com
Tue Jul 29 16:47:40 UTC 2014


Make sure to report the failure (usually exiting) in case of memory
allocation failures.
---
 src/ext2fs-c.c |  4 ++++
 src/init.c     | 13 +++++++++++++
 2 files changed, 17 insertions(+)

diff --git a/src/ext2fs-c.c b/src/ext2fs-c.c
index a265ad9..99f4d3c 100644
--- a/src/ext2fs-c.c
+++ b/src/ext2fs-c.c
@@ -615,6 +615,10 @@ ext2_copy_file (ext2_filsys fs, const char *src, const char *dest)
       if (fp == NULL)
 	goto cont;
       new_dirname = malloc (PATH_MAX+1);
+      if (new_dirname == NULL) {
+	pclose (fp);
+	goto cont;
+      }
       if (fgets (new_dirname, PATH_MAX, fp) == NULL) {
 	pclose (fp);
 	goto cont;
diff --git a/src/init.c b/src/init.c
index 73efdff..6b3dc7e 100644
--- a/src/init.c
+++ b/src/init.c
@@ -307,6 +307,11 @@ insmod (const char *filename)
   errno = 0;
   size = 0;
 
+  if (!buf) {
+    perror("malloc");
+    exit (EXIT_FAILURE);
+  }
+
 #ifdef HAVE_LZMA_STATIC
   if (ends_with(filename, ".xz")) {
     lzma_stream strm = LZMA_STREAM_INIT;
@@ -350,6 +355,10 @@ insmod (const char *filename)
           const size_t num =  tmpsize - strm.avail_out;
           if (num > capacity) {
                buf = (char*) realloc (buf, size*2);
+               if (!buf) {
+                    perror("realloc");
+                    exit (EXIT_FAILURE);
+               }
                capacity = size;
           }
           memcpy (buf+size, tmp_out, num);
@@ -380,6 +389,10 @@ insmod (const char *filename)
   while ((num = gzread (gzfp, tmp, tmpsize)) > 0) {
     if (num > capacity) {
       buf = (char*) realloc (buf, size*2);
+      if (!buf) {
+        perror("realloc");
+        exit (EXIT_FAILURE);
+      }
       capacity = size;
     }
     memcpy (buf+size, tmp, num);
-- 
1.9.3




More information about the Libguestfs mailing list