Skip to content

Commit 23c0113

Browse files
koh-shmatzbot
authored andcommitted
[ruby/stringio] fix: prevent segfault in StringIO#seek with SEEK_END
on null device (ruby/stringio#137) Fixes segmentation fault when calling `seek` with `SEEK_END` on null device StringIO created by `StringIO.new(nil)`. ```bash ruby -e "require 'stringio'; StringIO.new(nil).seek(0, IO::SEEK_END)" ``` I tested with below versions. ```bash [koh@Kohs-MacBook-Pro] ~ % ruby -v;gem info stringio;sw_vers ruby 3.4.5 (2025-07-16 revision ruby/stringio@20cda200d3) +PRISM [arm64-darwin24] *** LOCAL GEMS *** stringio (3.1.2) Authors: Nobu Nakada, Charles Oliver Nutter Homepage: https://github.com/ruby/stringio Licenses: Ruby, BSD-2-Clause Installed at (default): /Users/koh/.local/share/mise/installs/ruby/3.4.5/lib/ruby/gems/3.4.0 Pseudo IO on String ProductName: macOS ProductVersion: 15.5 BuildVersion: 24F74 [koh@Kohs-MacBook-Pro] ~ % ``` ruby/stringio@9399747bf9
1 parent 60ca525 commit 23c0113

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

ext/stringio/stringio.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -837,7 +837,11 @@ strio_seek(int argc, VALUE *argv, VALUE self)
837837
offset = ptr->pos;
838838
break;
839839
case 2:
840-
offset = RSTRING_LEN(ptr->string);
840+
if (NIL_P(ptr->string)) {
841+
offset = 0;
842+
} else {
843+
offset = RSTRING_LEN(ptr->string);
844+
}
841845
break;
842846
default:
843847
error_inval("invalid whence");

test/stringio/test_stringio.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,16 @@ def test_null
7070
assert_nil io.getc
7171
end
7272

73+
def test_seek_null
74+
io = StringIO.new(nil)
75+
assert_equal(0, io.seek(0, IO::SEEK_SET))
76+
assert_equal(0, io.pos)
77+
assert_equal(0, io.seek(0, IO::SEEK_CUR))
78+
assert_equal(0, io.pos)
79+
assert_equal(0, io.seek(0, IO::SEEK_END)) # This should not segfault
80+
assert_equal(0, io.pos)
81+
end
82+
7383
def test_truncate
7484
io = StringIO.new("")
7585
io.puts "abc"

0 commit comments

Comments
 (0)