From 5221eff69f918085b96e51b282d44d215ff04766 Mon Sep 17 00:00:00 2001 From: Zufu Liu Date: Fri, 6 Dec 2024 10:12:46 +1100 Subject: Feature [feature-requests:#1537]. Avoid truncation potential with PerformSort. Use string_view to improve safety. --- src/AutoComplete.cxx | 24 +++++++++++------------- src/AutoComplete.h | 1 - 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/AutoComplete.cxx b/src/AutoComplete.cxx index d49144684..57a3073f9 100644 --- a/src/AutoComplete.cxx +++ b/src/AutoComplete.cxx @@ -186,25 +186,23 @@ void AutoComplete::SetList(const char *list) { } std::string sortedList; - char item[maxItemLen]; for (size_t i = 0; i < sortMatrix.size(); ++i) { - int wordLen = IndexSort.indices[sortMatrix[i] * 2 + 2] - IndexSort.indices[sortMatrix[i] * 2]; - if (wordLen > maxItemLen-2) - wordLen = maxItemLen - 2; - memcpy(item, list + IndexSort.indices[sortMatrix[i] * 2], wordLen); - if ((i+1) == sortMatrix.size()) { + const unsigned index = sortMatrix[i] * 2; + // word length include trailing typesep and separator + const int wordLen = IndexSort.indices[index + 2] - IndexSort.indices[index]; + const std::string_view item(list + IndexSort.indices[index], wordLen); + sortedList += item; + if ((i + 1) == sortMatrix.size()) { // Last item so remove separator if present - if ((wordLen > 0) && (item[wordLen-1] == separator)) - wordLen--; + if (!item.empty() && item.back() == separator) { + sortedList.pop_back(); + } } else { // Item before last needs a separator - if ((wordLen == 0) || (item[wordLen-1] != separator)) { - item[wordLen] = separator; - wordLen++; + if (item.empty() || item.back() != separator) { + sortedList += separator; } } - item[wordLen] = '\0'; - sortedList += item; } for (int i = 0; i < static_cast(sortMatrix.size()); ++i) sortMatrix[i] = i; diff --git a/src/AutoComplete.h b/src/AutoComplete.h index 6afdf7c3e..ce8edd1d6 100644 --- a/src/AutoComplete.h +++ b/src/AutoComplete.h @@ -18,7 +18,6 @@ class AutoComplete { std::string fillUpChars; char separator; char typesep; // Type separator - enum { maxItemLen=1000 }; std::vector sortMatrix; public: -- cgit v1.2.3