Skip to content

Commit be749d7

Browse files
committed
Fix crash of cJSON_GetObjectItemCaseSensitive when calling it on arrays
1 parent cb1df2f commit be749d7

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

cJSON.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1781,7 +1781,7 @@ static cJSON *get_object_item(const cJSON * const object, const char * const nam
17811781
current_element = object->child;
17821782
if (case_sensitive)
17831783
{
1784-
while ((current_element != NULL) && (strcmp(name, current_element->string) != 0))
1784+
while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0))
17851785
{
17861786
current_element = current_element->next;
17871787
}
@@ -1794,6 +1794,10 @@ static cJSON *get_object_item(const cJSON * const object, const char * const nam
17941794
}
17951795
}
17961796

1797+
if ((current_element == NULL) || (current_element->string == NULL)) {
1798+
return NULL;
1799+
}
1800+
17971801
return current_element;
17981802
}
17991803

tests/misc_tests.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,28 @@ static void cjson_get_object_item_case_sensitive_should_get_object_items(void)
127127
cJSON_Delete(item);
128128
}
129129

130+
static void cjson_get_object_item_should_not_crash_with_array(void) {
131+
cJSON *array = NULL;
132+
cJSON *found = NULL;
133+
array = cJSON_Parse("[1]");
134+
135+
found = cJSON_GetObjectItem(array, "name");
136+
TEST_ASSERT_NULL(found);
137+
138+
cJSON_Delete(array);
139+
}
140+
141+
static void cjson_get_object_item_case_sensitive_should_not_crash_with_array(void) {
142+
cJSON *array = NULL;
143+
cJSON *found = NULL;
144+
array = cJSON_Parse("[1]");
145+
146+
found = cJSON_GetObjectItemCaseSensitive(array, "name");
147+
TEST_ASSERT_NULL(found);
148+
149+
cJSON_Delete(array);
150+
}
151+
130152
static void typecheck_functions_should_check_type(void)
131153
{
132154
cJSON invalid[1];
@@ -535,6 +557,8 @@ int CJSON_CDECL main(void)
535557
RUN_TEST(cjson_array_foreach_should_not_dereference_null_pointer);
536558
RUN_TEST(cjson_get_object_item_should_get_object_items);
537559
RUN_TEST(cjson_get_object_item_case_sensitive_should_get_object_items);
560+
RUN_TEST(cjson_get_object_item_should_not_crash_with_array);
561+
RUN_TEST(cjson_get_object_item_case_sensitive_should_not_crash_with_array);
538562
RUN_TEST(typecheck_functions_should_check_type);
539563
RUN_TEST(cjson_should_not_parse_to_deeply_nested_jsons);
540564
RUN_TEST(cjson_set_number_value_should_set_numbers);

0 commit comments

Comments
 (0)