Project

General

Profile

Actions

Bug #22237

closed

GC.auto_compact corrupts a String or segfaults from String#tr with dup or gsub

Bug #22237: GC.auto_compact corrupts a String or segfaults from String#tr with dup or gsub

Added by curi (Elliot Temple) 5 days ago. Updated 3 days ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 4.0.6 (2026-07-14 revision 03b6d3f889) +YJIT +PRISM [arm64-darwin25]
Backport:
[ruby-core:126353]

Description

GC.auto_compact = true can cause memory corruption or segfaults with string methods. Ruby 4.0.6, arm64 macOS, YJIT enabled, 100 runs: 35 clean, 27 corruption, 38 segfault. I also saw the issue with Ruby 4.0.4, x86-64 Debian, or YJIT disabled.

# ruby --disable-gems autocompact-test.rb

puts RUBY_DESCRIPTION
input = "aaa"
iterations = Integer(ENV.fetch("ITERATIONS", 10_000_000))
$stdout.sync = true
GC.auto_compact = true
Object.new # increases chance of memory corruption or segfault

iterations.times do |i|
  s = input.tr("\u0080", "\u20AC").dup
  # gsub(/x/, "") instead of dup works too
  # the tr, gsub and dup should all return the original input bytes

  unless s == input
    warn "Corrupt output at iteration #{i}: #{s.bytes.inspect}"
    warn GC.stat.slice(:major_gc_count, :compact_count, :total_moved_objects).inspect
    exit 2
  end
end

Updated by luke-gru (Luke Gruber) 4 days ago Actions #1 [ruby-core:126362]

  • Backport changed from 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN to 4.0: REQUIRED

Thanks for the good repro, it was very helpful. I have a patch here.

Updated by luke-gru (Luke Gruber) 3 days ago Actions #2 [ruby-core:126368]

  • Status changed from Open to Closed
Actions

Also available in: PDF Atom