Segmentation fault when reading data from a socket using std.Io

Your problem is here. You are creating a copy of the interface, not getting a pointer to the stream reader’s interface variable. The details have been discussed in many other threads (namely Zig 0.15.1 reader/writer: Don't make copies of @fieldParentPtr()-based interfaces). You can read that if you want more detailed discussion.

In short, your fix is to capture the Stream.Reader in a variable and get the interface by pointer.

const std = @import("std");
const Io = std.Io;
const print = std.debug.print;

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const address = try Io.net.IpAddress.parseIp4("127.0.0.1", 8080);
    var server = try Io.net.IpAddress.listen(address, io, .{ .reuse_address = true });
    while (true) {
        var stream = try server.accept(io);
        var read_buffer: [1024]u8 = undefined;
        var stream_reader = stream.reader(io, &read_buffer);
        var rdr = &stream_reader.interface;
        _ = try rdr.peek(1);
        // The following also works
        _ = try stream_reader.interface.peek(1);
    }
}
4 Likes