Przeglądaj źródła

parse_array: goto fail error handling

Makes the control flow easier to reason about and fixes a few potential
memory leaks.
Max Bruckner 8 lat temu
rodzic
commit
99cd9af7d5
1 zmienionych plików z 12 dodań i 5 usunięć
  1. 12 5
      cJSON.c

+ 12 - 5
cJSON.c

@@ -1127,7 +1127,7 @@ static const unsigned char *parse_array(cJSON *item, const unsigned char *value,
     {
     {
         /* not an array! */
         /* not an array! */
         *ep = value;
         *ep = value;
-        return NULL;
+        goto fail;
     }
     }
 
 
     item->type = cJSON_Array;
     item->type = cJSON_Array;
@@ -1142,13 +1142,13 @@ static const unsigned char *parse_array(cJSON *item, const unsigned char *value,
     if (!item->child)
     if (!item->child)
     {
     {
         /* memory fail */
         /* memory fail */
-        return NULL;
+        goto fail;
     }
     }
     /* skip any spacing, get the value. */
     /* skip any spacing, get the value. */
     value = skip(parse_value(child, skip(value), ep));
     value = skip(parse_value(child, skip(value), ep));
     if (!value)
     if (!value)
     {
     {
-        return NULL;
+        goto fail;
     }
     }
 
 
     /* loop through the comma separated array elements */
     /* loop through the comma separated array elements */
@@ -1158,7 +1158,7 @@ static const unsigned char *parse_array(cJSON *item, const unsigned char *value,
         if (!(new_item = cJSON_New_Item()))
         if (!(new_item = cJSON_New_Item()))
         {
         {
             /* memory fail */
             /* memory fail */
-            return NULL;
+            goto fail;
         }
         }
         /* add new item to end of the linked list */
         /* add new item to end of the linked list */
         child->next = new_item;
         child->next = new_item;
@@ -1170,7 +1170,7 @@ static const unsigned char *parse_array(cJSON *item, const unsigned char *value,
         if (!value)
         if (!value)
         {
         {
             /* memory fail */
             /* memory fail */
-            return NULL;
+            goto fail;
         }
         }
     }
     }
 
 
@@ -1183,6 +1183,13 @@ static const unsigned char *parse_array(cJSON *item, const unsigned char *value,
     /* malformed. */
     /* malformed. */
     *ep = value;
     *ep = value;
 
 
+fail:
+    if (item->child != NULL)
+    {
+        cJSON_Delete(item->child);
+        item->child = NULL;
+    }
+
     return NULL;
     return NULL;
 }
 }