looping over stack allocated struct works expected:
node.value 1
node 0x000000000000000000000001
But the code segfaults when looping over heap allocated struct with the following error:
node.value 1
node 0xaaaaaaaaaaaaaaaa00000001
Segmentation fault at address 0x0
zig/learn/struct_default_null.zig:8:51: 0x10ff0b8d3 in printNodes (struct_default_null)
std.debug.print("node.value {d}\n", .{node.value});
^
???:?:?: 0xa075894898558947 in ??? (???)
Unwind information for `???:0xa075894898558947` was not available, trace may be incomplete
[1] 20380 abort zig run struct_default_null.zig
I only used packed struct because i cannot @bitCast normal struct, but it also crashes.
I can see the value of the next is undefined in heap allocation.
Why is it like that and why the while loop even does next iteration? Shouldn’t the next be null?
A default value is a comptime-known value that is implicitly passed when using the Type{ .field = value, ... } syntax. But you’re creating a new one with an allocator it’s like using var instance: Type = undefined. It’s… undefined. Here, you’re dereferencing an undefined pointer. Of course it’ll segfault.
I actually read that doc about allocation is not initialization when it was posted, but I totally forgot about it, maybe I wasn’t paying attention or didn’t try to practice it actually writing zig code.
I should try to write more zig code to actually learn zig. I only keep reading the posts and articles, but never writing any.
My favorite way of doing initialization is to have 2 “constructors”, one for stack allocation and the other one for heap allocation. Using your linked list example it would be something like this: