Bug #22701
open`Array#pack("p")` / `("P")` address goes stale after `GC.compact`, and `String#unpack("p")` raises "non associated pointer"
Description
Array#pack("p") and ("P") write RSTRING_PTR(str) into the result. The source strings are remembered in a hidden Array (pack.c str_associate) so that unpack("p") can find them again. That Array references them as movable. When GC.compact (or auto-compaction) moves an embedded Str
ing, its bytes move with the object slot, so the address stored in the packed string no longer matches. unpack("p") compares the stored address with RSTRING_PTR of each associated string (pack.c associated_pointer), finds no match, and raises.
The same stale address is what a user hands to C code via Fiddle and similar libraries, which is the main purpose of "p"/"P". After compaction it points to the old slot. Non-embedded strings can also be affected when compaction re-embeds them (gc.c, the T_STRING case in the reference-upda
te pass that calls rb_str_make_embedded).
Reproduction:
a = "alpha"
pk = [a].pack("p")
10.times do |i|
200.times { "x" * 3 }
GC.compact
begin
pk.unpack("p")
rescue => e
puts "after #{i + 1} GC.compact: #{e.class}: #{e.message}"
break
end
end
Actual:
Expected: pk.unpack("p") returns ["alpha"], and the address in pk stays valid while pk is alive, as it does without compaction.
Possible fix / question: pin the strings referenced by "p"/"P", for example by keeping the associates in a TypedData whose mark function uses rb_gc_mark (pinning) instead of an Array. Pinning also stops the re-embedding, because that code skips pinned objects. This changes what Racto r.make_shareable does with a packed string: it currently traverses the hidden Array and freezes the source strings. Alternatively, document that the address is not stable across compaction.
Version: ruby 4.1.0dev (2026-12-01T20:47:52Z master 0d8198a37c) +PRISM [x86_64-linux]