From af79954d15b4e56e1db88cefb3c19b557423c35c Mon Sep 17 00:00:00 2001 From: Roman Donchenko Date: Thu, 6 Jun 2024 04:27:58 +0300 Subject: [PATCH] drivenum.cpp: fix undefined behavior in find_approximate_matches (#12441) * If `it` points to the last element of `penalty`, the `resize` call invalidates it, and the subsequent call to `emplace` is undefined. This causes a crash in MSVC debug mode. * Fix it by resizing _after_ emplacing. --- src/emu/drivenum.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/emu/drivenum.cpp b/src/emu/drivenum.cpp index 3db8a3334d5..84158749189 100644 --- a/src/emu/drivenum.cpp +++ b/src/emu/drivenum.cpp @@ -260,7 +260,7 @@ void driver_enumerator::find_approximate_matches(std::string const &string, std: { // allocate memory to track the penalty value std::vector > penalty; - penalty.reserve(count); + penalty.reserve(count + 1); std::u32string const search(ustr_from_utf8(normalize_unicode(string, unicode_normalization_form::D, true))); std::string composed; std::u32string candidate; @@ -303,9 +303,9 @@ void driver_enumerator::find_approximate_matches(std::string const &string, std: auto const it(std::upper_bound(penalty.begin(), penalty.end(), std::make_pair(curpenalty, index))); if (penalty.end() != it) { - if (penalty.size() >= count) - penalty.resize(count - 1); penalty.emplace(it, curpenalty, index); + if (penalty.size() > count) + penalty.pop_back(); } else if (penalty.size() < count) {