From 58f5deba70c0e9d21836fda4b1fee041fef69e16 Mon Sep 17 00:00:00 2001 From: Maciej Date: Thu, 8 Dec 2022 18:30:04 +0100 Subject: [PATCH] AK: Unref old m_data in String's move assignment We were overridding the data pointer without unreffing it, causing a memory leak when assigning a String. --- AK/String.cpp | 3 +++ Tests/AK/TestString.cpp | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/AK/String.cpp b/AK/String.cpp index ac443a0ce5..c92c3c54eb 100644 --- a/AK/String.cpp +++ b/AK/String.cpp @@ -181,6 +181,9 @@ String::String(String&& other) String& String::operator=(String&& other) { + if (!is_short_string()) + m_data->unref(); + m_data = exchange(other.m_data, nullptr); return *this; } diff --git a/Tests/AK/TestString.cpp b/Tests/AK/TestString.cpp index c453e6d74c..3cc88317a9 100644 --- a/Tests/AK/TestString.cpp +++ b/Tests/AK/TestString.cpp @@ -24,6 +24,13 @@ TEST_CASE(construct_empty) EXPECT_EQ(empty, ""sv); } +TEST_CASE(move_assignment) +{ + String string1 = MUST(String::from_utf8("hello"sv)); + string1 = MUST(String::from_utf8("friends!"sv)); + EXPECT_EQ(string1, "friends!"sv); +} + TEST_CASE(short_strings) { #ifdef AK_ARCH_64_BIT