Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/hash_map.c
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ extern "C"

#include <string.h>
#include <stdio.h>
#include <stdint.h>

#include "rcutils/allocator.h"
#include "rcutils/error_handling.h"
Expand Down Expand Up @@ -86,7 +87,10 @@ static rcutils_ret_t hash_map_allocate_new_map(
rcutils_array_list_t ** map, size_t capacity,
const rcutils_allocator_t * allocator)
{
*map = allocator->allocate(capacity * sizeof(rcutils_hash_map_impl_t), allocator->state);
if (0 == capacity || capacity > SIZE_MAX / sizeof(rcutils_array_list_t)) {
return RCUTILS_RET_BAD_ALLOC;
}
*map = allocator->allocate(capacity * sizeof(rcutils_array_list_t), allocator->state);
if (NULL == *map) {
return RCUTILS_RET_BAD_ALLOC;
}
Expand Down Expand Up @@ -240,7 +244,7 @@ static size_t next_power_of_two(size_t v)
v |= v >> shf;
}
v++;
return v > 1 ? v : 1;
return v;
}

rcutils_ret_t
Expand Down
16 changes: 16 additions & 0 deletions test/test_hash_map.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,22 @@ TEST_F(HashMapBaseTest, init_map_initial_capacity_not_power_of_two) {
EXPECT_EQ(RCUTILS_RET_OK, ret) << rcutils_get_error_string().str;
}

TEST_F(HashMapBaseTest, init_map_initial_capacity_overflow_fails) {
rcutils_ret_t ret = rcutils_hash_map_init(
&map, SIZE_MAX, sizeof(uint32_t), sizeof(uint32_t),
test_hash_map_uint32_hash_func, test_uint32_cmp, &allocator);
EXPECT_EQ(RCUTILS_RET_BAD_ALLOC, ret) << rcutils_get_error_string().str;
EXPECT_EQ(nullptr, map.impl);
}

TEST_F(HashMapBaseTest, init_map_allocation_size_overflow_fails) {
rcutils_ret_t ret = rcutils_hash_map_init(
&map, (SIZE_MAX >> 1) + 1, sizeof(uint32_t), sizeof(uint32_t),
test_hash_map_uint32_hash_func, test_uint32_cmp, &allocator);
EXPECT_EQ(RCUTILS_RET_BAD_ALLOC, ret) << rcutils_get_error_string().str;
EXPECT_EQ(nullptr, map.impl);
}

TEST_F(HashMapBaseTest, init_map_key_size_zero_fails) {
rcutils_ret_t ret = rcutils_hash_map_init(
&map, 2, 0, sizeof(uint32_t),
Expand Down