From ad5bb80cb9ae7d43c2aa6e1155e6937eeecdf809 Mon Sep 17 00:00:00 2001 From: ping Date: Sat, 18 Apr 2026 13:01:28 +0800 Subject: [PATCH] Fix memory leak in cJSON_AddItemReferenceToObject on string alloc failure --- cJSON.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/cJSON.c b/cJSON.c index 88c2d95b..69ea81af 100644 --- a/cJSON.c +++ b/cJSON.c @@ -2139,12 +2139,26 @@ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) { + cJSON *reference = NULL; + if ((object == NULL) || (string == NULL)) { return false; } - return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); + reference = create_reference(item, &global_hooks); + if (reference == NULL) + { + return false; + } + + if (!add_item_to_object(object, string, reference, &global_hooks, false)) + { + cJSON_Delete(reference); + return false; + } + + return true; } CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)