From 0cbf579ca16aff194c4437a1079d04cd949d362d Mon Sep 17 00:00:00 2001 From: Albert Astals Cid Date: Tue, 25 Jun 2024 00:53:00 +0200 Subject: [PATCH] QString::assign: Don't crash when passed an empty range Pick-to: 6.7 Change-Id: I7c02abeb1bd8fa5a8609f163a5a722c2c236fc2b Reviewed-by: Giuseppe D'Angelo Reviewed-by: Thiago Macieira (cherry picked from commit aa2cfb58089dcf46d14606964e30d1c695b64393) Reviewed-by: Qt Cherry-pick Bot --- src/corelib/text/qstring.h | 6 ++++-- .../auto/corelib/text/qstring/tst_qstring.cpp | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/corelib/text/qstring.h b/src/corelib/text/qstring.h index 98c2f3cdb0e..9355df57561 100644 --- a/src/corelib/text/qstring.h +++ b/src/corelib/text/qstring.h @@ -520,11 +520,13 @@ public: return *this; } else if constexpr (QtPrivate::IsCompatibleChar8Type::value) { assign_helper_char8(first, last); - d.data()[d.size] = u'\0'; + if (d.constAllocatedCapacity()) + d.data()[d.size] = u'\0'; return *this; } else { d.assign(first, last, [](QChar ch) -> char16_t { return ch.unicode(); }); - d.data()[d.size] = u'\0'; + if (d.constAllocatedCapacity()) + d.data()[d.size] = u'\0'; return *this; } } diff --git a/tests/auto/corelib/text/qstring/tst_qstring.cpp b/tests/auto/corelib/text/qstring/tst_qstring.cpp index 92ea5b013d6..3c40aacda5d 100644 --- a/tests/auto/corelib/text/qstring/tst_qstring.cpp +++ b/tests/auto/corelib/text/qstring/tst_qstring.cpp @@ -3668,6 +3668,25 @@ void tst_QString::assign() QCOMPARE(str.size(), 3); } // QString &assign(InputIterator, InputIterator) + { + // This needs to be on its own to ensure we call them on empty str + QString str; + + const char16_t c16[] = u"٩(⁎❛ᴗ❛⁎)۶ 🤷"; + std::u16string c16str(c16); + str.assign(c16str.begin(), c16str.begin()); + QCOMPARE(str.size(), 0); + } + { +#ifndef QT_NO_CAST_FROM_ASCII + // This needs to be on its own to ensure we call them on empty str + QString str; + const char c8[] = "a©☻🂤"; // [1, 2, 3, 4] bytes in utf-8 code points + std::string c8str(c8); + str.assign(c8str.begin(), c8str.begin()); + QCOMPARE(str.size(), 0); +#endif + } { // Forward iterator versions QString str;