From: "ko1 (Koichi Sasada) via ruby-core" Date: 2026-12-02T07:44:03+00:00 Subject: [ruby-core:127794] [Ruby Bug#22701] `Array#pack("p")` / `("P")` address goes stale after `GC.compact`, and `String#unpack("p")` raises "non associated pointer" Issue #22701 has been reported by ko1 (Koichi Sasada). ---------------------------------------- Bug #22701: `Array#pack("p")` / `("P")` address goes stale after `GC.compact`, and `String#unpack("p")` raises "non associated pointer" https://bugs.ruby-lang.org/issues/22701 * Author: ko1 (Koichi Sasada) * Status: Open * Backport: 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN ---------------------------------------- `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:** ```ruby 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:** ``` after 2 GC.compact: ArgumentError: non associated pointer ``` **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]` -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/