From 567212739318d7e14f1d91db12292bd1166b17c0 Mon Sep 17 00:00:00 2001 From: Lieven Hey Date: Tue, 17 Oct 2023 14:36:33 +0200 Subject: [PATCH] fix out of range access start was set to current + 1 which will cause undefined behavior if current is the last element this patch adds a check for this and wraps around in that case fixes: #526 --- src/models/search.h | 8 +++++++- tests/modeltests/tst_search.cpp | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/models/search.h b/src/models/search.h index 93c5f2580..6d706e6fd 100644 --- a/src/models/search.h +++ b/src/models/search.h @@ -29,7 +29,13 @@ int search_impl(iter begin, iter end, iter current, SearchFunc searchFunc, EndRe if (begin == end) return -1; - auto start = current + 1; + iter start; + if (current != end) { + start = current + 1; + } else { + start = begin; + } + auto found = std::find_if(start, end, searchFunc); if (found != end) { diff --git a/tests/modeltests/tst_search.cpp b/tests/modeltests/tst_search.cpp index 931790693..307978fdf 100644 --- a/tests/modeltests/tst_search.cpp +++ b/tests/modeltests/tst_search.cpp @@ -82,6 +82,26 @@ private slots: 3); } } + + void testArrayIsEmpty() + { + const std::array testArray; + + for (int i = 0; i < 2; i++) { + QCOMPARE(search( + testArray, i, Direction::Forward, [](int) { return true; }, [] {}), + -1); + } + } + + void testOutOfRangeIfCurrentIsEnd() + { + const std::array testArray = {0}; + + QCOMPARE(search( + testArray, 1, Direction::Forward, [](int i) { return i == 0; }, [] {}), + 0); + } }; QTEST_GUILESS_MAIN(TestSearch)