]> git.apps.os.sepia.ceph.com Git - ceph.git/commitdiff
rgw/rgw_formats.cc: fix realloc memory leak
authorDanny Al-Gaaf <danny.al-gaaf@bisect.de>
Mon, 27 Oct 2014 10:09:01 +0000 (11:09 +0100)
committerSage Weil <sage@redhat.com>
Mon, 27 Oct 2014 19:44:26 +0000 (12:44 -0700)
Fix handling of realloc. If realloc() fails it returns NULL, assigning
the return value of realloc() directly to the pointer without checking
for the result will lead to a memory leak in error case.

Use a temporary pointer to hold the result of realloc(). In error case
print error and exit, otherwise assign it to the pointer we want to realloc.

Fix also error checks for malloc to fail as soon as malloc fails and
don't try to run realloc again after failed malloc.

Signed-off-by: Danny Al-Gaaf <danny.al-gaaf@bisect.de>
src/rgw/rgw_formats.cc

index 2ea0e3e69cbb911a4f8dfc6be0c2ccb0e6af376b..8a6ef072fa5a91e64669cd4cfd46274881e7e66d 100644 (file)
@@ -197,16 +197,23 @@ done:
   if (!buf) {
     max_len = max(LARGE_ENOUGH_BUF, size);
     buf = (char *)malloc(max_len);
+    if (!buf) {
+      cerr << "ERROR: RGWFormatter_Plain::write_data: failed allocating " << max_len << " bytes" << std::endl;
+      goto done_free;
+    }
   }
 
   if (len + size > max_len) {
     max_len = len + size + LARGE_ENOUGH_BUF;
-    buf = (char *)realloc(buf, max_len);
-  }
-  if (!buf) {
-    cerr << "ERROR: RGWFormatter_Plain::write_data: failed allocating " << max_len << " bytes" << std::endl;
-    goto done_free;
+    void *_realloc = NULL;
+    if ((_realloc = realloc(buf, max_len)) == NULL) {
+      cerr << "ERROR: RGWFormatter_Plain::write_data: failed allocating " << max_len << " bytes" << std::endl;
+      goto done_free;
+    } else {
+      buf = (char *)_realloc;
+    }
   }
+
   pos = len;
   if (len)
     pos--; // squash null termination