Hi folks, I’m new to zig and trying to build a linked list. I managed to write the following code but it does not work as expected. I think this has something to do with memory allocation.
My code:
const std = @import("std");
pub const LinkedList = struct {
const Self = @This();
pub const Node = struct { val: i32, next: ?*Node = null };
head: ?*Node,
tail: ?*Node,
length: u32,
pub fn new() LinkedList {
return LinkedList{ .head = null, .tail = null, .length = 0 };
}
pub fn insert(self: *Self, v: i32) void {
var newNode = Node{ .val = v };
if (self.tail != null) {
var t: *Node = self.tail.?;
t.next = &newNode;
self.tail = &newNode;
} else {
self.head = &newNode;
self.tail = &newNode;
}
self.length += 1;
}
pub fn traverse(self: Self) void {
if (self.head == null) {
std.debug.print("head is null. nothing to do...\n", .{});
return;
}
var h = self.head;
while (true) {
if (h == null) {
break;
}
const ptr: *Node = h.?;
std.debug.print("val :{}\n", .{ptr.val});
h = ptr.next;
}
}
pub fn len(self: Self) u32 {
return self.length;
}
};
pub fn main() !void {
var list = LinkedList.new();
list.insert(10);
list.insert(20);
list.traverse();
std.debug.print("len :{}\n", .{list.len()});
}
Output and the error:
zig run main.zig
val :20
val :-1605007032
General protection exception (no address available)
/home/thilina/git/dsa-zig/linked-list/main.zig:46:47: 0x1033a9b in traverse (main)
std.debug.print("val :{}\n", .{ptr.val});
/home/thilina/git/dsa-zig/linked-list/main.zig:64:18: 0x10338cd in main (main)
list.traverse();
^
/usr/lib/zig/std/start.zig:511:37: 0x1033864 in posixCallMainAndExit (main)
const result = root.main() catch |err| {
^
/usr/lib/zig/std/start.zig:253:5: 0x10333a1 in _start (main)
asm volatile (switch (native_arch) {
^
???:?:?: 0x0 in ??? (???)
Aborted (core dumped)
My questions are,
- Why does it print 20 first when I try to traverse the linked list? Head should point to the node with the value 10 because it is added first and I don’t change the value of head after that?
- Why does the optional pointer has a garbage value for the second node?
Thank you very much in advance!