From 10251039d5cb20611cc6ab5f8145f580d1d23dc4 Mon Sep 17 00:00:00 2001 From: Vitor Hideyoshi Date: Wed, 15 Apr 2026 20:28:11 -0300 Subject: [PATCH] fix: prevent underflow in array_pop when called on an empty array --- src/dynamic_array.h | 3 +++ src/test_dynamic_array.c | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/dynamic_array.h b/src/dynamic_array.h index e4cdbfe..764b328 100644 --- a/src/dynamic_array.h +++ b/src/dynamic_array.h @@ -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) diff --git a/src/test_dynamic_array.c b/src/test_dynamic_array.c index 0f23ea6..8bab02b 100644 --- a/src/test_dynamic_array.c +++ b/src/test_dynamic_array.c @@ -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);