#Why it's giving memory leak error at create?

1 messages · Page 1 of 1 (latest)

harsh salmon
#
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;
}
lethal hound
#

do you free it at some point?

harsh salmon
lethal hound
#

are you calling deinit?

harsh salmon
#

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 ??? (???)
lethal hound
#

your dequeue is the problem, i think

#

since you pop it without freeing it

harsh salmon
#

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

lethal hound
#

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?

harsh salmon
#

yeah @lethal hound good point

light pelican