Prechádzať zdrojové kódy

UB/Crash in entt::insertion_sort (#167)

Michele Caini 7 rokov pred
rodič
commit
c9fddedbf1
2 zmenil súbory, kde vykonal 19 pridanie a 10 odobranie
  1. 12 10
      src/entt/core/algorithm.hpp
  2. 7 0
      test/entt/core/algorithm.cpp

+ 12 - 10
src/entt/core/algorithm.hpp

@@ -54,19 +54,21 @@ struct insertion_sort final {
      */
     template<typename It, typename Compare = std::less<>>
     void operator()(It first, It last, Compare compare = Compare{}) const {
-        auto it = first + 1;
+        if(first != last) {
+            auto it = first + 1;
 
-        while(it != last) {
-            auto value = *it;
-            auto pre = it;
+            while(it != last) {
+                auto value = *it;
+                auto pre = it;
 
-            while(pre != first && compare(value, *(pre-1))) {
-                *pre = *(pre-1);
-                --pre;
-            }
+                while(pre != first && compare(value, *(pre-1))) {
+                    *pre = *(pre-1);
+                    --pre;
+                }
 
-            *pre = value;
-            ++it;
+                *pre = value;
+                ++it;
+            }
         }
     }
 };

+ 7 - 0
test/entt/core/algorithm.cpp

@@ -24,3 +24,10 @@ TEST(Algorithm, InsertionSort) {
         ASSERT_LT(arr[i], arr[i+1]);
     }
 }
+
+TEST(Algorithm, InsertionSortEmptyContainer) {
+    std::vector<int> vec{};
+    entt::insertion_sort sort;
+    // this should crash with asan enabled if we break the constraint
+    sort(vec.begin(), vec.end());
+}