The segmentation fault error I can't understant why

Hello everyone! I’m a new bee of zig and get a segmentation fault when doing some programming practice that I can’t figure out why :sob:
TODL: when using the captured inner of an optional pointer variable by if statement that segmentation fault error is got. code:

const Node = struct {
    left: ?*Node,
    right: ?*Node,
    height: i32,
}

fn get_height(node: ?*Node) i32 {
    if (node) |n| {
         return n.height; // segmentation fault error here, I don't know why since n is valid here I think.
    }
    return 0;

The full code at Untitled (wftjtnuy) - PasteCode.io, download and save to main.zig, and run zig test main.zig :

3/3 main.test.remove...Segmentation fault at address 0x76551a5510d0
/home/lianxm/github/zig-playgroud/avltree/src/main.zig:227:45: 0x1049660 in update_height (test)
                const left = get_height(node.left);
                                            ^
/home/lianxm/github/zig-playgroud/avltree/src/main.zig:120:39: 0x10e07d9 in remove (test)
                    root.update_height();
                                      ^
/home/lianxm/github/zig-playgroud/avltree/src/main.zig:38:40: 0x10e070b in remove (test)
                const res = root.remove(key);
                                       ^
/home/lianxm/github/zig-playgroud/avltree/src/main.zig:297:22: 0x10e05ea in test.remove (test)
    assert(avl.remove("C").? == 3);
                     ^
/home/lianxm/bins/zig/lib/compiler/test_runner.zig:208:25: 0x10e7d4c in mainTerminal (test)
        if (test_fn.func()) |_| {
                        ^
/home/lianxm/bins/zig/lib/compiler/test_runner.zig:57:28: 0x10e1c50 in main (test)
        return mainTerminal();
                           ^
/home/lianxm/bins/zig/lib/std/start.zig:608:22: 0x10e11a6 in posixCallMainAndExit (test)
            root.main();
                     ^
/home/lianxm/bins/zig/lib/std/start.zig:248:5: 0x10e0dcf in _start (test)
    asm volatile (switch (native_arch) {
    ^
???:?:?: 0x0 in ??? (???)
error: the following test command crashed:
/home/lianxm/github/zig-playgroud/avltree/.zig-cache/o/64fd7c657c613702f9ffade9b3582968/test --seed=0x98a9a639
``

That stack trace is showing a segfault when you dereference node.left before calling get_height, not a segfault in get_height.

1 Like

It seems that defer node.deinit(); in remove_internal frees the node and then update_height is called.

Welcome to ziggit :slight_smile:

3 Likes

I’m sorry for the wrong information and thanks you reply! :grinning:

Thanks! the node.deinit() is destory the node tree recursively I not realise before. A typical use after free mistake :grimacing:

1 Like