Skip to content

Commit

Permalink
fix out of range access
Browse files Browse the repository at this point in the history
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
  • Loading branch information
lievenhey committed Oct 19, 2023
1 parent 1a22291 commit 5672127
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/models/search.h
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
20 changes: 20 additions & 0 deletions tests/modeltests/tst_search.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,26 @@ private slots:
3);
}
}

void testArrayIsEmpty()
{
const std::array<int, 0> testArray;

for (int i = 0; i < 2; i++) {
QCOMPARE(search(
testArray, i, Direction::Forward, [](int) { return true; }, [] {}),
-1);
}
}

void testOutOfRangeIfCurrentIsEnd()
{
const std::array<int, 1> testArray = {0};

QCOMPARE(search(
testArray, 1, Direction::Forward, [](int i) { return i == 0; }, [] {}),
0);
}
};

QTEST_GUILESS_MAIN(TestSearch)
Expand Down

0 comments on commit 5672127

Please sign in to comment.