Skip to content

Commit

Permalink
Fix undefined behavior in search.
Browse files Browse the repository at this point in the history
We use following line to clamp the search depth in some range:
Depth d = std::clamp(newDepth - r, 1, newDepth + 1);

Through negative extension its possible that the maximum value becomes smaller than the minimum value but then the behavior is undefined (see https://en.cppreference.com/w/cpp/algorithm/clamp). So replace this line with a save implementation.

Remark:
We have in recent master already one line where up to 3 negative extensions are possible which would could trigger this undefined behavior but we had the luck (or bad luck depending on the view point) that this until now was not discovered. Recent negative extension tests by @fauzi shows then this undefined behavior with wrong bench numbers.

Bench: 1334248
  • Loading branch information
locutus2 committed Nov 16, 2023
1 parent f9d8717 commit a7daf8f
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/search.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1178,7 +1178,12 @@ Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, boo
// In general we want to cap the LMR depth search at newDepth, but when
// reduction is negative, we allow this move a limited search extension
// beyond the first move depth. This may lead to hidden double extensions.
Depth d = std::clamp(newDepth - r, 1, newDepth + 1);
// NOTE:
// In the past this was realized via the std::clamp function but this has
// an undefined behavior if max value < min value which was triggered
// through some more negative extension tests.
// So it was replaced with this save implementation.
Depth d = std::max(1, std::min(newDepth - r, newDepth + 1));

value = -search<NonPV>(pos, ss + 1, -(alpha + 1), -alpha, d, true);

Expand Down

0 comments on commit a7daf8f

Please sign in to comment.