From a6225f95717f8294c3ec0f2cbcce78dd5833fccc Mon Sep 17 00:00:00 2001 From: Bailey Thompson Date: Mon, 17 Aug 2020 02:49:10 -0400 Subject: [PATCH] Add overflow checking to array (#111) --- src/array.c | 9 +++++++-- tst/test_array.c | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/array.c b/src/array.c index c5b3961..6d0ee75 100644 --- a/src/array.c +++ b/src/array.c @@ -30,8 +30,7 @@ static const size_t data_size_offset = sizeof(size_t); static const size_t data_ptr_offset = 2 * sizeof(size_t); /** - * Initializes an array. If the multiplication of the element count and the - * data size overflows, it is undefined behavior. + * Initializes an array. * * @param element_count the number of elements in the array; must not be * negative @@ -47,6 +46,12 @@ array array_init(const size_t element_count, const size_t data_size) if (data_size == 0) { return NULL; } + if (element_count * data_size / data_size != element_count) { + return NULL; + } + if (data_ptr_offset + element_count * data_size < data_ptr_offset) { + return NULL; + } init = malloc(data_ptr_offset + element_count * data_size); if (!init) { return NULL; diff --git a/tst/test_array.c b/tst/test_array.c index 0de7cab..0eaacd4 100644 --- a/tst/test_array.c +++ b/tst/test_array.c @@ -5,6 +5,10 @@ static void test_invalid_init(void) { assert(!array_init(1, 0)); + /* These tests rely on this. */ + assert(sizeof(size_t) == sizeof(unsigned long)); + assert(!array_init(ULONG_MAX, ULONG_MAX)); + assert(!array_init(1, ULONG_MAX)); } static void test_empty_array(void)