mirror of
https://github.com/bkthomps/Containers.git
synced 2025-11-16 04:24:47 +00:00
Add overflow checking to array (#111)
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user