pub fn enqueue(self: *Self, element: T) !void {
const new_node = try self.allocator.create(Node);
new_node.* = .{
.data = element,
.next = null,
};
if (self.head == null) {
self.head = new_node;
return;
}
var temp = self.head;
while (temp.?.next) |t| {
temp = t.next;
}
temp.?.next = new_node;
}
#Why it's giving memory leak error at create?
1 messages · Page 1 of 1 (latest)
do you free it at some point?
I am destroying them
pub fn deinit(self: *Self) void {
var temp = self.head;
while (temp) |t| {
const next = t.next;
self.allocator.destroy(t);
temp = next;
}
self.head = null;
}
are you calling deinit?
Yeah @lethal hound
var q: Queue(u32) = .init(allocator);
defer q.deinit();
try q.enqueue(2);
try q.enqueue(3);
while (!q.empty()) {
const pop = try q.dequeue();
std.debug.print("{}\n", .{pop});
}
2
3
error(gpa): memory address 0x104380000 leaked:
/Users/ashu2427/Coding/zig-projects/zim/src/queue.zig:30:55: 0x1042a1483 in enqueue (zim)
const new_node = try self.allocator.create(Node);
^
/Users/ashu2427/Coding/zig-projects/zim/src/main.zig:67:18: 0x1042a1833 in main (zim)
try q.enqueue(2);
^
/Users/ashu2427/Library/Application Support/Code/User/globalStorage/ziglang.vscode-zig/zig/aarch64-macos-0.15.2/lib/std/start.zig:627:37: 0x1042a1ef7 in main (zim)
const result = root.main() catch |err| {
^
???:?:?: 0x18dd11d53 in ??? (???)
error(gpa): memory address 0x104380010 leaked:
/Users/ashu2427/Coding/zig-projects/zim/src/queue.zig:30:55: 0x1042a1483 in enqueue (zim)
const new_node = try self.allocator.create(Node);
^
/Users/ashu2427/Coding/zig-projects/zim/src/main.zig:68:18: 0x1042a18a3 in main (zim)
try q.enqueue(3);
^
/Users/ashu2427/Library/Application Support/Code/User/globalStorage/ziglang.vscode-zig/zig/aarch64-macos-0.15.2/lib/std/start.zig:627:37: 0x1042a1ef7 in main (zim)
const result = root.main() catch |err| {
^
???:?:?: 0x18dd11d53 in ??? (???)
but it should deinit anyways right. I am not freeing when popping. So at the end it should free right. Or should I free at the time of pop
no? since the queue doesn't hold a reference to it anymore, look at your deinit code, if it doesn't have a reference anymore, how does it free the popped values?
yeah @lethal hound good point
not relavent, but if you always append to the list, you might want to store a pointer to the last item so you dont have to traverse it each time, this will simplify code and should be faster.
though it does store an extra pointer worth of memory