mirror of
https://github.com/bkthomps/Containers.git
synced 2025-12-09 00:53:22 +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);
|
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;
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
Reference in New Issue
Block a user