I was playing around with zig, when I produced the following code which is totally questionable:
const std = @import("std");
pub const Foo = struct {
buffer: [5586936]u8 = undefined,
pub fn init(self: Foo) *Foo {
const x = @constCast(&self);
return x;
}
pub fn dosomething(_: *Foo) void {}
};
pub fn main() !void {
var p = (Foo{}).init();
p.dosomething();
}
This code has several problems, but what intrigued me the most was that when I run it with the zig build run command it runs without any errors, but if I run zig build -Doptimize=Debug && ./zig-out/bin/executable it throws a segmentation fault error.
Could someone explain why the behavior is different for the two commands?
Another interesting point is that if I decrease the buffer size from 5586936 to 5586935, the error does not occur with either command.