diff --git a/cJSON.c b/cJSON.c index 8903e4c2..8b028ac1 100644 --- a/cJSON.c +++ b/cJSON.c @@ -406,10 +406,16 @@ CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) return NULL; } /* return NULL if the object is corrupted */ - if (object->valuestring == NULL || valuestring == NULL) + if (object->valuestring == NULL) { return NULL; } + /* NULL valuestring causes error with strlen and should be treated separately */ + if (valuestring == NULL) + { + object->valuestring = NULL; + return NULL; + } if (strlen(valuestring) <= strlen(object->valuestring)) { strcpy(object->valuestring, valuestring); diff --git a/tests/misc_tests.c b/tests/misc_tests.c index 48fb6ec2..ba3e003e 100644 --- a/tests/misc_tests.c +++ b/tests/misc_tests.c @@ -444,6 +444,7 @@ static void cjson_functions_should_not_crash_with_null_pointers(void) TEST_ASSERT_FALSE(cJSON_Compare(NULL, item, false)); TEST_ASSERT_NULL(cJSON_SetValuestring(NULL, "test")); 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); */