From a1300d37975c855795fada9eceec99701747c1d6 Mon Sep 17 00:00:00 2001 From: Zaggy1024 Date: Thu, 10 Nov 2022 19:54:43 -0600 Subject: [PATCH] AK: Don't crash in HashTable::clear_with_capacity on an empty table When calling clear_with_capacity on an empty HashTable/HashMap, a null deref would occur when trying to memset() m_buckets. Checking that it has capacity before clearing fixes the issue. --- AK/HashTable.h | 2 ++ Tests/AK/TestHashTable.cpp | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/AK/HashTable.h b/AK/HashTable.h index ad6f7de16e0..b2d9b6fe087 100644 --- a/AK/HashTable.h +++ b/AK/HashTable.h @@ -291,6 +291,8 @@ public: } void clear_with_capacity() { + if (m_capacity == 0) + return; if constexpr (!Detail::IsTriviallyDestructible) { for (auto* bucket : *this) bucket->~T(); diff --git a/Tests/AK/TestHashTable.cpp b/Tests/AK/TestHashTable.cpp index 410681a352c..57a7db00852 100644 --- a/Tests/AK/TestHashTable.cpp +++ b/Tests/AK/TestHashTable.cpp @@ -309,3 +309,12 @@ TEST_CASE(reinsertion) map.remove("__sak"); map.set("__sak"); } + +TEST_CASE(clear_with_capacity_when_empty) +{ + HashTable map; + map.clear_with_capacity(); + map.set(0); + map.set(1); + VERIFY(map.size() == 2); +}