Jelajahi Sumber

civetweb.c: fix realloc handling

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().

Fix for:
[src/civetweb.c:409]: (error) Common realloc mistake: 'data' nulled but
not freed upon failure

Signed-off-by: Danny Al-Gaaf <danny.al-gaaf@bisect.de>
Danny Al-Gaaf 11 tahun lalu
induk
melakukan
a18401f0eb
1 mengubah file dengan 5 tambahan dan 2 penghapusan
  1. 5 2
      src/civetweb.c

+ 5 - 2
src/civetweb.c

@@ -441,14 +441,16 @@ static void * mg_realloc_ex(void * memory, size_t newsize, const char * file, un
 
 
     char mallocStr[256];
     char mallocStr[256];
     void * data;
     void * data;
+    void * _realloc;
     size_t oldsize;
     size_t oldsize;
 
 
     if (newsize) {
     if (newsize) {
         if (memory) {
         if (memory) {
             data = (void *)(((char*)memory)-sizeof(size_t));
             data = (void *)(((char*)memory)-sizeof(size_t));
             oldsize = *(size_t*)data;
             oldsize = *(size_t*)data;
-            data = realloc(data, newsize+sizeof(size_t));
-            if (data) {
+            _realloc = realloc(data, newsize+sizeof(size_t));
+            if (_realloc) {
+                data = _realloc;
                 totalMemUsed -= oldsize;
                 totalMemUsed -= oldsize;
                 sprintf(mallocStr, "MEM: %p %5u r-free  %7u %4u --- %s:%u\n", memory, oldsize, totalMemUsed, blockCount, file, line);
                 sprintf(mallocStr, "MEM: %p %5u r-free  %7u %4u --- %s:%u\n", memory, oldsize, totalMemUsed, blockCount, file, line);
 #if defined(_WIN32)
 #if defined(_WIN32)
@@ -471,6 +473,7 @@ static void * mg_realloc_ex(void * memory, size_t newsize, const char * file, un
 #else
 #else
                 DEBUG_TRACE("MEM: realloc failed\n");
                 DEBUG_TRACE("MEM: realloc failed\n");
 #endif
 #endif
+                return _realloc;
             }
             }
         } else {
         } else {
             data = mg_malloc_ex(newsize, file, line);
             data = mg_malloc_ex(newsize, file, line);