Hi, so basically I’m running into an issue, as a teaching exercise I’m trying to implement a simple linked list but, the problem is that my implementation panics, and I think I know why I’m just unsure why my approach doesn’t work I’ve commended the code with how I transpile that in my brain into C
const std = @import("std");
pub fn List(comptime T: type) type {
return struct {
const Self = @This();
head: ?*Node = null,
tail: ?*Node = null,
size: usize = 0,
pub const Node = struct {
next: ?*Node = null,
data: T = undefined,
pub fn create(allocator: std.mem.Allocator) !?*Node {
return (try allocator.create(Node));
}
pub fn destroy(node: *Node, allocator: std.mem.Allocator) void {
allocator.destroy(node);
}
};
// to me this is the equivalent of C where you do :
// list *list_create(void) {
// list *list = (list*) malloc(sizeof(list));
// if (!list)
// return null;
// else
// return list;
// }
pub fn init(allocator: std.mem.Allocator) !?*Self {
return (try allocator.create(Self));
}
// to me this is the equivalent of C where you do :
// list list_create(void) {
// return (list){.head = NULL, .tail = NULL .size = 0};
// }
pub fn correct_init() Self {
return Self{
.head = null,
.tail = null,
.size = 0,
};
}
pub fn deinit(list: *Self, allocator: std.mem.Allocator) void {
var curr: ?*Node = list.head;
var temp: *Node = undefined;
while (curr) |node| {
temp = node;
curr = node.next;
temp.destroy(allocator);
}
allocator.destroy(list);
}
};
}
test "list_type_size" {
try std.testing.expect(@sizeOf(List(i32)) == 24);
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const maybe_list = try List(i32).init(allocator);
if (maybe_list) |list| {
defer list.deinit(allocator);
}
}
I’m looking for explanation about my init function specifically, when using lldb the panics occurs when I try to access the member function deinit, I’ve looked at the standard std.SinglyLinkedList implementation, and I can’t figure where is the memory coming from, I’ve tried to look into the forum, and found a few post that where trying to explain it but it’s still doesn’t click for me, so if anyone would be kind enough to explain to me why my approach doesn’t work, I would really appreciate. Thanks