From 79e2ad0817261a01323572a46806fde6ee8441b7 Mon Sep 17 00:00:00 2001 From: PeterAlfredLee Date: Tue, 3 Mar 2026 17:08:56 +0800 Subject: [PATCH] fix: prevent NULL pointer dereference in cJSON_SetNumberHelper Add NULL check at the beginning of cJSON_SetNumberHelper to prevent segmentation fault when called with NULL object pointer. The function now returns NAN (Not-a-Number) when object is NULL, consistent with error handling patterns in other cJSON functions. This fixes a Denial of Service vulnerability (CWE-476) where an attacker could crash applications using the cJSON library by triggering this function with a NULL pointer. Changes: - cJSON.c: Add NULL check in cJSON_SetNumberHelper - tests/misc_tests.c: Add test case and math.h include Security: Fixes NULL pointer dereference vulnerability --- cJSON.c | 5 +++++ tests/misc_tests.c | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/cJSON.c b/cJSON.c index f16a7bccd..88c2d95b3 100644 --- a/cJSON.c +++ b/cJSON.c @@ -410,6 +410,11 @@ static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_bu /* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) { + if (object == NULL) + { + return (double)NAN; + } + if (number >= INT_MAX) { object->valueint = INT_MAX; diff --git a/tests/misc_tests.c b/tests/misc_tests.c index 7c616479e..fe2325e96 100644 --- a/tests/misc_tests.c +++ b/tests/misc_tests.c @@ -23,6 +23,7 @@ #include #include #include +#include #include "unity/examples/unity_config.h" #include "unity/src/unity.h" @@ -478,8 +479,8 @@ static void cjson_functions_should_not_crash_with_null_pointers(void) TEST_ASSERT_NULL(cJSON_SetValuestring(corruptedString, "test")); TEST_ASSERT_NULL(cJSON_SetValuestring(item, NULL)); cJSON_Minify(NULL); - /* skipped because it is only used via a macro that checks for NULL */ - /* cJSON_SetNumberHelper(NULL, 0); */ + /* cJSON_SetNumberHelper should handle NULL gracefully */ + TEST_ASSERT_TRUE(isnan(cJSON_SetNumberHelper(NULL, 0))); /* restore corrupted item2 to delete it */ item2->prev = originalPrev;