Skip to content

find() on 0-sized unordered_map causes division by 0 #1200

@TheComet

Description

@TheComet

We have this edge case in our platform:

const auto map = etl::make_unordered_map<int, int>(
  // {5, 10},
  // {7, 3},
);

const auto it = map.find(5);  // crash

The crash occurs in:

    size_type get_bucket_index(const_key_reference key) const
    {
      return key_hash_function(key) % number_of_buckets;
    }

in

    const_iterator find(const_key_reference key) const
    {
      size_t index = get_bucket_index(key);

because number_of_buckets == 0.

My suggested fix is to clamp the capacity to >=1 like so:

  template <typename TKey, typename T, typename THash = etl::hash<TKey>, typename TKeyEqual = etl::equal_to<TKey>, typename... TPairs>
  constexpr auto make_unordered_map(TPairs&&... pairs) -> etl::unordered_map<
    TKey,
    T,
    (sizeof...(TPairs) == 0 ? 1 : sizeof...(TPairs)),
    (sizeof...(TPairs) == 0 ? 1 : sizeof...(TPairs)),
    THash,
    TKeyEqual>
  {
    return { etl::forward<TPairs>(pairs)... };
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    Status

    To do

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions