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

This commit is contained in:
Michele Caini
2018-12-11 14:17:39 +01:00
parent 530bbbe4c5
commit c9fddedbf1
2 changed files with 19 additions and 10 deletions

View File

@@ -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;
}
}
};

View File

@@ -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());
}