1
0
mirror of https://github.com/SerenityOS/serenity synced 2024-07-05 20:34:56 +00:00

AK: Ensure assigned-to Strings are dereferenced if needed

If we assign to an existing non-short string, we must dereference its
StringData object to prevent leaking that data.
This commit is contained in:
Timothy Flynn 2023-11-28 08:59:47 -05:00 committed by Andreas Kling
parent 82398e5724
commit 6aa334767f
2 changed files with 25 additions and 0 deletions

View File

@ -215,10 +215,15 @@ String& String::operator=(String&& other)
String& String::operator=(String const& other)
{
if (&other != this) {
if (!is_short_string())
m_data->unref();
m_data = other.m_data;
if (!is_short_string())
m_data->ref();
}
return *this;
}

View File

@ -39,6 +39,26 @@ TEST_CASE(move_assignment)
EXPECT_EQ(string1, "friends!"sv);
}
TEST_CASE(copy_assignment)
{
auto test = [](auto string1, auto string2) {
string1 = string2;
EXPECT_EQ(string1, string2);
};
test(String {}, String {});
test(String {}, "abc"_string);
test(String {}, "long string"_string);
test("abc"_string, String {});
test("abc"_string, "abc"_string);
test("abc"_string, "long string"_string);
test("long string"_string, String {});
test("long string"_string, "abc"_string);
test("long string"_string, "long string"_string);
}
TEST_CASE(short_strings)
{
#ifdef AK_ARCH_64_BIT