diff --git a/src/value.c b/src/value.c index ba9908e..2aae326 100644 --- a/src/value.c +++ b/src/value.c @@ -509,7 +509,10 @@ int json_array_remove(json_t *json, size_t index) json_decref(array->table[index]); - array_move(array, index, index + 1, array->entries - index); + /* If we're removing the last element, nothing has to be moved */ + if(index < array->entries - 1) + array_move(array, index, index + 1, array->entries - index); + array->entries--; return 0; diff --git a/test/suites/api/test_array.c b/test/suites/api/test_array.c index 4585db9..3ff8f1a 100644 --- a/test/suites/api/test_array.c +++ b/test/suites/api/test_array.c @@ -206,6 +206,7 @@ static void test_insert(void) static void test_remove(void) { json_t *array, *five, *seven; + int i; array = json_array(); five = json_integer(5); @@ -253,6 +254,19 @@ static void test_remove(void) json_array_get(array, 2) != seven) fail("remove works incorrectly"); + json_decref(array); + + array = json_array(); + for(i = 0; i < 4; i++) { + json_array_append(array, five); + json_array_append(array, seven); + } + if(json_array_size(array) != 8) + fail("unable to append 8 items to array"); + + /* Remove the last element from a "full" array. */ + json_array_remove(array, 7); + json_decref(five); json_decref(seven); json_decref(array);