fix: prevent underflow in array_pop when called on an empty array
This commit is contained in:
@@ -63,6 +63,9 @@ typedef struct {
|
|||||||
#define array_pop(arr) \
|
#define array_pop(arr) \
|
||||||
do { \
|
do { \
|
||||||
ArrayHeader *header = array_get_header(arr); \
|
ArrayHeader *header = array_get_header(arr); \
|
||||||
|
if (header->size == 0) { \
|
||||||
|
break; \
|
||||||
|
} \
|
||||||
header->size--; \
|
header->size--; \
|
||||||
} while (0)
|
} while (0)
|
||||||
|
|
||||||
|
|||||||
@@ -81,6 +81,24 @@ void test_array_pop_decrements_size(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void test_array_pop_on_empty_is_noop(void) {
|
||||||
|
int *arr = NULL;
|
||||||
|
array_create(arr);
|
||||||
|
|
||||||
|
array_push_value(arr, 99);
|
||||||
|
TEST_ASSERT_EQUAL(1, array_get_header(arr)->size);
|
||||||
|
TEST_ASSERT_EQUAL(99, arr[0]);
|
||||||
|
|
||||||
|
array_pop(arr);
|
||||||
|
TEST_ASSERT_EQUAL(0, array_get_header(arr)->size);
|
||||||
|
|
||||||
|
array_pop(arr); // should not underflow
|
||||||
|
TEST_ASSERT_EQUAL(0, array_get_header(arr)->size);
|
||||||
|
|
||||||
|
array_destroy(arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void test_array_get_capacity_default(void) {
|
void test_array_get_capacity_default(void) {
|
||||||
int *arr = NULL;
|
int *arr = NULL;
|
||||||
array_create(arr);
|
array_create(arr);
|
||||||
@@ -152,6 +170,7 @@ int main(void)
|
|||||||
RUN_TEST(test_array_push_value);
|
RUN_TEST(test_array_push_value);
|
||||||
RUN_TEST(test_array_push_multiple_values);
|
RUN_TEST(test_array_push_multiple_values);
|
||||||
RUN_TEST(test_array_pop_decrements_size);
|
RUN_TEST(test_array_pop_decrements_size);
|
||||||
|
RUN_TEST(test_array_pop_on_empty_is_noop);
|
||||||
RUN_TEST(test_array_get_capacity_default);
|
RUN_TEST(test_array_get_capacity_default);
|
||||||
RUN_TEST(test_array_size_capacity_relationship);
|
RUN_TEST(test_array_size_capacity_relationship);
|
||||||
RUN_TEST(test_array_push_beyond_capacity);
|
RUN_TEST(test_array_push_beyond_capacity);
|
||||||
|
|||||||
Reference in New Issue
Block a user