]> Zhao Yanbai Git Server - minix.git/commitdiff
libmthread: resolve memory leaks on exception path 49/3349/1
authorDavid van Moolenbroek <david@minix3.org>
Fri, 5 Aug 2016 10:26:36 +0000 (10:26 +0000)
committerDavid van Moolenbroek <david@minix3.org>
Fri, 5 Aug 2016 11:17:30 +0000 (11:17 +0000)
If libmthread runs into a memory allocation failure while attempting
to enlarge its thread pool, it does not free up any preliminary
allocations made so far.

Reported by dcb314.

This closes #152.

Change-Id: Ib882a4544e4802a0eb0a53446b43997876cde633

minix/lib/libmthread/allocate.c

index 9d2c458408c1becf2e57b70be573c31e20caa6fc..f34862aa655e1dacddda7670892dcb5631a954c6 100644 (file)
@@ -194,12 +194,22 @@ static int mthread_increase_thread_pool(void)
        new_tcb[i] = malloc(sizeof(mthread_tcb_t));
        if (new_tcb[i] == NULL) {
                mthread_debug("Can't allocate space for tcb");
+               /* Undo the allocations made so far. */
+               while (i-- > old_no_threads)
+                       free(new_tcb[i]);
+               if (old_no_threads > 0) {
+                       new_tcb = realloc(threads, old_no_threads *
+                           sizeof(mthread_tcb_t *));
+                       if (new_tcb == NULL)
+                               mthread_panic("Unable to shrink tcb array");
+               } else
+                       free(new_tcb);
                return(-1);
        }
        memset(new_tcb[i], '\0', sizeof(mthread_tcb_t)); /* Clear entry */
   }
 
-  /* We can breath again, let's tell the others about the good news */
+  /* We can breathe again, let's tell the others about the good news */
   threads = new_tcb; 
   no_threads = new_no_threads;