From 622f3f14b6928ee4fe3afa96db0250eb9da32e7a Mon Sep 17 00:00:00 2001 From: nobu Date: Mon, 26 Jan 2015 02:37:51 +0000 Subject: [PATCH] string.c: terminate when embedded * string.c (str_make_independent_expand): terminate String when moved from heap to embedded. [Fix GH-821]. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@49405 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 +++++ string.c | 1 + test/-ext-/string/test_cstr.rb | 9 +++++++++ 3 files changed, 15 insertions(+) diff --git a/ChangeLog b/ChangeLog index 9dc983a8cb..3ac6ab493f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Mon Jan 26 11:37:49 2015 Dave Stevens + + * string.c (str_make_independent_expand): terminate String when + moved from heap to embedded. [Fix GH-821]. + Sun Jan 25 12:04:12 2015 Nobuyoshi Nakada * array.c (flatten): no need to call to_ary method on elements diff --git a/string.c b/string.c index c8707c62a6..ffe2e6233a 100644 --- a/string.c +++ b/string.c @@ -1593,6 +1593,7 @@ str_make_independent_expand(VALUE str, long expand) ptr = RSTRING(str)->as.heap.ptr; STR_SET_EMBED(str); memcpy(RSTRING(str)->as.ary, ptr, len); + RSTRING(str)->as.ary[len] = '\0'; /* Ensure string is terminated */ STR_SET_EMBED_LEN(str, len); return; } diff --git a/test/-ext-/string/test_cstr.rb b/test/-ext-/string/test_cstr.rb index 6f2fdef3d4..72a9dd6dfa 100644 --- a/test/-ext-/string/test_cstr.rb +++ b/test/-ext-/string/test_cstr.rb @@ -86,6 +86,15 @@ class Test_StringCStr < Test::Unit::TestCase } end + def test_embedded_from_heap + gh821 = "[GH-821]" + embedded_string = "abcdefghi" + string = embedded_string.gsub("efg", "123") + {}[string] = 1 + non_terminated = "#{string}#{nil}" + assert_nil(Bug::String.cstr_term_char(non_terminated), gh821) + end + def assert_wchars_term_char(str) result = {} WCHARS.map do |enc|