diff --git a/cJSON.c b/cJSON.c index cac1164b..5eb7abc3 100644 --- a/cJSON.c +++ b/cJSON.c @@ -2327,6 +2327,22 @@ CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON replacement->next = item->next; replacement->prev = item->prev; + if (item->string) + { + /* duplicate name from source to replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)item->string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + } + if (replacement->next != NULL) { replacement->next->prev = replacement; @@ -2378,19 +2394,6 @@ static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSO return false; } - /* replace the name in the replacement */ - if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) - { - cJSON_free(replacement->string); - } - replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); - if (replacement->string == NULL) - { - return false; - } - - replacement->type &= ~cJSON_StringIsConst; - return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); } diff --git a/tests/misc_tests.c b/tests/misc_tests.c index 94dd91aa..c444614f 100644 --- a/tests/misc_tests.c +++ b/tests/misc_tests.c @@ -345,6 +345,16 @@ static void cjson_replace_item_in_object_should_preserve_name(void) TEST_ASSERT_TRUE(root->child == replacement); TEST_ASSERT_EQUAL_STRING("child", replacement->string); + /* now test the same, but with replaceitemviapointer */ + child = cJSON_GetObjectItemCaseSensitive(root, "child"); + TEST_ASSERT_NOT_NULL(child); + replacement = cJSON_CreateNumber(3); + TEST_ASSERT_NOT_NULL(replacement); + cJSON_ReplaceItemViaPointer(root, child, replacement); + + TEST_ASSERT_TRUE(root->child == replacement); + TEST_ASSERT_EQUAL_STRING("child", replacement->string); + cJSON_Delete(replacement); }