Skip to content

Commit

Permalink
[Bug #18154] Fix memory leak in String#initialize
Browse files Browse the repository at this point in the history
String#initialize can leak memory when called on a string that is marked
with STR_NOFREE because it does not unset the STR_NOFREE flag.
  • Loading branch information
peterzhu2118 committed Sep 8, 2021
1 parent 0b9242f commit 5d81554
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion string.c
Expand Up @@ -1734,7 +1734,7 @@ rb_str_init(int argc, VALUE *argv, VALUE str)
const size_t osize = RSTRING(str)->as.heap.len + TERM_LEN(str);
char *new_ptr = ALLOC_N(char, (size_t)capa + termlen);
memcpy(new_ptr, old_ptr, osize < size ? osize : size);
FL_UNSET_RAW(str, STR_SHARED);
FL_UNSET_RAW(str, STR_SHARED|STR_NOFREE);
RSTRING(str)->as.heap.ptr = new_ptr;
}
else if (STR_HEAP_SIZE(str) != (size_t)capa + termlen) {
Expand Down
10 changes: 10 additions & 0 deletions test/ruby/test_string.rb
Expand Up @@ -105,6 +105,16 @@ def test_initialize_memory_leak
CODE
end

# Bug #18154
def test_initialize_nofree_memory_leak
assert_no_memory_leak([], <<-PREP, <<-CODE, rss: true)
code = proc {0.to_s.__send__(:initialize, capacity: 10000)}
1_000.times(&code)
PREP
100_000.times(&code)
CODE
end

def test_AREF # '[]'
assert_equal("A", S("AooBar")[0])
assert_equal("B", S("FooBaB")[-1])
Expand Down

0 comments on commit 5d81554

Please sign in to comment.