Skip to content

Commit 5d81554

Browse files
committed
[Bug #18154] Fix memory leak in String#initialize
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.
1 parent 0b9242f commit 5d81554

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

string.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1734,7 +1734,7 @@ rb_str_init(int argc, VALUE *argv, VALUE str)
17341734
const size_t osize = RSTRING(str)->as.heap.len + TERM_LEN(str);
17351735
char *new_ptr = ALLOC_N(char, (size_t)capa + termlen);
17361736
memcpy(new_ptr, old_ptr, osize < size ? osize : size);
1737-
FL_UNSET_RAW(str, STR_SHARED);
1737+
FL_UNSET_RAW(str, STR_SHARED|STR_NOFREE);
17381738
RSTRING(str)->as.heap.ptr = new_ptr;
17391739
}
17401740
else if (STR_HEAP_SIZE(str) != (size_t)capa + termlen) {

test/ruby/test_string.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,16 @@ def test_initialize_memory_leak
105105
CODE
106106
end
107107

108+
# Bug #18154
109+
def test_initialize_nofree_memory_leak
110+
assert_no_memory_leak([], <<-PREP, <<-CODE, rss: true)
111+
code = proc {0.to_s.__send__(:initialize, capacity: 10000)}
112+
1_000.times(&code)
113+
PREP
114+
100_000.times(&code)
115+
CODE
116+
end
117+
108118
def test_AREF # '[]'
109119
assert_equal("A", S("AooBar")[0])
110120
assert_equal("B", S("FooBaB")[-1])

0 commit comments

Comments
 (0)