Skip to content

Instantly share code, notes, and snippets.

@matu3ba
Last active February 17, 2022 00:40
Show Gist options
  • Save matu3ba/07ea081b07639e7ecceb13173083484f to your computer and use it in GitHub Desktop.
Save matu3ba/07ea081b07639e7ecceb13173083484f to your computer and use it in GitHub Desktop.
miscompilation from comptime writing of buffer
const std = @import("std");
const mem = std.mem;
const strings = [_][]const u8{ "Hello", "There" };
pub fn main() !void {
comptime var buf_size = 0;
inline for (strings) |str| {
buf_size += str.len;
}
const len_offsets = strings.len;
comptime var buf = [_]u8{0} ** buf_size;
comptime var offsets = [_]u64{0} ** len_offsets;
//@compileLog(strings.len);
//@compileLog(strings[0].len);
//@compileLog(strings[1].len);
//@compileLog(buf);
//@compileLog(offsets);
comptime var cur_offset = 0;
inline for (strings) |str, i| {
//@compileLog(cur_offset);
offsets[i] = cur_offset;
//@compileLog(cur_offset);
//@compileLog(str.len);
//@compileLog(cur_offset + str.len);
//@compileLog(str.len);
//@compileLog(buf[cur_offset .. cur_offset + str.len].len);
mem.copy(u8, buf[cur_offset .. cur_offset + str.len], str);
cur_offset += str.len;
}
std.debug.print("{d}\n", .{buf_size});
std.debug.print("{d}\n", .{len_offsets});
std.debug.print("{s}\n", .{buf});
std.debug.print("{d}\n", .{offsets});
std.debug.print("{d}\n", .{cur_offset});
}
:!zig run enumOffsetArray.zig
Segmentation fault at address 0x202cd8
/home/user/dev/git/zig/zig/master/lib/std/mem.zig:221:19: 0x212508 in std.mem.copy (enumOffsetArray)
dest[i] = s;
^
/home/user/dev/git/zig/tryzig/enumOffsetArray.zig:27:17: 0x22d370 in main (enumOffsetArray)
mem.copy(u8, buf[cur_offset .. cur_offset + str.len], str);
^
/home/user/dev/git/zig/zig/master/lib/std/start.zig:561:37: 0x2268aa in std.start.callMain (enumOffsetArray)
const result = root.main() catch |err| {
^
/home/user/dev/git/zig/zig/master/lib/std/start.zig:495:12: 0x20745e in std.start.callMainWithArgs (enumOffsetArray)
return @call(.{ .modifier = .always_inline }, callMain, .{});
^
/home/user/dev/git/zig/zig/master/lib/std/start.zig:409:17: 0x2064f6 in std.start.posixCallMainAndExit (enumOffsetArray)
std.os.exit(@call(.{ .modifier = .always_inline }, callMainWithArgs, .{ argc, argv, envp }));
^
/home/user/dev/git/zig/zig/master/lib/std/start.zig:322:5: 0x206302 in std.start._start (enumOffsetArray)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment