fix: prevent underflow in array_pop when called on an empty array

This commit is contained in:
2026-04-15 20:28:11 -03:00
parent 8c6e7e035b
commit 10251039d5
2 changed files with 22 additions and 0 deletions

View File

@@ -63,6 +63,9 @@ typedef struct {
#define array_pop(arr) \
do { \
ArrayHeader *header = array_get_header(arr); \
if (header->size == 0) { \
break; \
} \
header->size--; \
} while (0)

View File

@@ -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) {
int *arr = NULL;
array_create(arr);
@@ -152,6 +170,7 @@ int main(void)
RUN_TEST(test_array_push_value);
RUN_TEST(test_array_push_multiple_values);
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_size_capacity_relationship);
RUN_TEST(test_array_push_beyond_capacity);