Просмотр исходного кода

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.
Zaggy1024 2 лет назад
Родитель
Сommit
a1300d3797
2 измененных файлов с 11 добавлено и 0 удалено
  1. 2 0
      AK/HashTable.h
  2. 9 0
      Tests/AK/TestHashTable.cpp

+ 2 - 0
AK/HashTable.h

@@ -291,6 +291,8 @@ public:
     }
     void clear_with_capacity()
     {
+        if (m_capacity == 0)
+            return;
         if constexpr (!Detail::IsTriviallyDestructible<T>) {
             for (auto* bucket : *this)
                 bucket->~T();

+ 9 - 0
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<int> map;
+    map.clear_with_capacity();
+    map.set(0);
+    map.set(1);
+    VERIFY(map.size() == 2);
+}