]> git.feebdaed.xyz Git - 0xmirror/cJSON.git/commitdiff
cJSON_DetachItemViaPointer: added test and fix for check for null in item->prev
authorNicolas Badoux <n.badoux@hotmail.com>
Sun, 25 Aug 2024 21:18:14 +0000 (23:18 +0200)
committerAlan Wang <wp_scut@163.com>
Fri, 30 Aug 2024 03:29:05 +0000 (11:29 +0800)
cJSON.c
tests/misc_tests.c

diff --git a/cJSON.c b/cJSON.c
index 483d0c0cd8c0a344fb23c43626e9803b3f7a2a5b..fe22bd83c5fab07266116ff1e2d074a42cd436bb 100644 (file)
--- a/cJSON.c
+++ b/cJSON.c
@@ -2204,7 +2204,7 @@ CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * c
 
 CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
 {
-    if ((parent == NULL) || (parent->child == NULL) || (item == NULL) || (item->prev == NULL))
+    if ((parent == NULL) || (item == NULL) || (item != parent->child && item->prev == NULL))
     {
         return NULL;
     }
index ba3e003e5d45253f4e07c786a59c899899300410..b9c59e71a58f9a0919ea80bfc92e64e1740562e8 100644 (file)
@@ -280,6 +280,21 @@ static void cjson_detach_item_via_pointer_should_detach_items(void)
     TEST_ASSERT_NULL_MESSAGE(parent->child, "Child of the parent wasn't set to NULL.");
 }
 
+static void cjson_detach_item_via_pointer_should_return_null_if_item_prev_is_null(void)
+{
+    cJSON list[2];
+    cJSON parent[1];
+
+    memset(list, '\0', sizeof(list));
+
+    /* link the list */
+    list[0].next = &(list[1]);
+
+    parent->child = &list[0];
+    TEST_ASSERT_NULL_MESSAGE(cJSON_DetachItemViaPointer(parent, &(list[1])), "Failed to detach in the middle.");
+    TEST_ASSERT_TRUE_MESSAGE(cJSON_DetachItemViaPointer(parent, &(list[0])) == &(list[0]), "Failed to detach in the middle.");
+}
+
 static void cjson_replace_item_via_pointer_should_replace_items(void)
 {
     cJSON replacements[3];
@@ -746,6 +761,7 @@ int CJSON_CDECL main(void)
     RUN_TEST(cjson_should_not_parse_to_deeply_nested_jsons);
     RUN_TEST(cjson_set_number_value_should_set_numbers);
     RUN_TEST(cjson_detach_item_via_pointer_should_detach_items);
+    RUN_TEST(cjson_detach_item_via_pointer_should_return_null_if_item_prev_is_null);
     RUN_TEST(cjson_replace_item_via_pointer_should_replace_items);
     RUN_TEST(cjson_replace_item_in_object_should_preserve_name);
     RUN_TEST(cjson_functions_should_not_crash_with_null_pointers);