Skip to content

Commit e327f1c

Browse files
committed
fix: fix NULL valuestring error
Fix NULL valuestring problem in cJSON_SetValuestring. This fixes #839 and CVE-2024-31755 Related issue #845
1 parent 5671646 commit e327f1c

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

cJSON.c

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,10 +406,17 @@ CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring)
406406
return NULL;
407407
}
408408
/* return NULL if the object is corrupted */
409-
if (object->valuestring == NULL || valuestring == NULL)
409+
if (object->valuestring == NULL)
410410
{
411411
return NULL;
412412
}
413+
/* NULL valuestring causes error with strlen and should be treated separately */
414+
if (valuestring == NULL)
415+
{
416+
cJSON_free(object->valuestring);
417+
object->valuestring = NULL;
418+
return NULL;
419+
}
413420
if (strlen(valuestring) <= strlen(object->valuestring))
414421
{
415422
strcpy(object->valuestring, valuestring);

tests/misc_tests.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,7 @@ static void cjson_functions_should_not_crash_with_null_pointers(void)
444444
TEST_ASSERT_FALSE(cJSON_Compare(NULL, item, false));
445445
TEST_ASSERT_NULL(cJSON_SetValuestring(NULL, "test"));
446446
TEST_ASSERT_NULL(cJSON_SetValuestring(corruptedString, "test"));
447+
TEST_ASSERT_NULL(cJSON_SetValuestring(item, NULL));
447448
cJSON_Minify(NULL);
448449
/* skipped because it is only used via a macro that checks for NULL */
449450
/* cJSON_SetNumberHelper(NULL, 0); */

0 commit comments

Comments
 (0)