Add overflow checking to array (#111)

This commit is contained in:
Bailey Thompson
2020-08-17 02:49:10 -04:00
committed by GitHub
parent 044a853994
commit a6225f9571
2 changed files with 11 additions and 2 deletions

View File

@@ -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); static const size_t data_ptr_offset = 2 * sizeof(size_t);
/** /**
* Initializes an array. If the multiplication of the element count and the * Initializes an array.
* data size overflows, it is undefined behavior.
* *
* @param element_count the number of elements in the array; must not be * @param element_count the number of elements in the array; must not be
* negative * negative
@@ -47,6 +46,12 @@ array array_init(const size_t element_count, const size_t data_size)
if (data_size == 0) { if (data_size == 0) {
return NULL; 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); init = malloc(data_ptr_offset + element_count * data_size);
if (!init) { if (!init) {
return NULL; return NULL;

View File

@@ -5,6 +5,10 @@
static void test_invalid_init(void) static void test_invalid_init(void)
{ {
assert(!array_init(1, 0)); 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) static void test_empty_array(void)