Don't leak on an OPENSSL_realloc() failure
authorMatt Caswell <matt@openssl.org>
Wed, 21 Sep 2016 14:49:28 +0000 (15:49 +0100)
committerMatt Caswell <matt@openssl.org>
Wed, 21 Sep 2016 19:30:25 +0000 (20:30 +0100)
If OPENSSL_sk_insert() calls OPENSSL_realloc() and it fails, it was leaking
the originally allocated memory.

Reviewed-by: Rich Salz <rsalz@openssl.org>
(cherry picked from commit 41bff723c6784cc846054a4fd4add6dbec8c2c64)

crypto/stack/stack.c

index 1d01936e003d739efa35f61cc8542d0a81d2dd64..43ddf30ac1f111874fb2afb692b03a02578d6153 100644 (file)
@@ -126,6 +126,7 @@ int OPENSSL_sk_insert(OPENSSL_STACK *st, const void *data, int loc)
 
     if (st->num_alloc <= (size_t)(st->num + 1)) {
         size_t doub_num_alloc = st->num_alloc * 2;
+        const char **tmpdata;
 
         /* Overflow checks */
         if (doub_num_alloc < st->num_alloc)
@@ -135,17 +136,12 @@ int OPENSSL_sk_insert(OPENSSL_STACK *st, const void *data, int loc)
         if (doub_num_alloc > SIZE_MAX / sizeof(char *))
             return 0;
 
-        st->data = OPENSSL_realloc((char *)st->data,
-                                   sizeof(char *) * doub_num_alloc);
-        if (st->data == NULL) {
-            /*
-             * Reset these counters to prevent subsequent operations on
-             * (now non-existing) heap memory
-             */
-            st->num_alloc = 0;
-            st->num = 0;
+        tmpdata = OPENSSL_realloc((char *)st->data,
+                                  sizeof(char *) * doub_num_alloc);
+        if (tmpdata == NULL)
             return 0;
-        }
+
+        st->data = tmpdata;
         st->num_alloc = doub_num_alloc;
     }
     if ((loc >= st->num) || (loc < 0)) {