BST table 实现段错误 (C)

BST table implementation segfault (C)

我一直在尝试使用二叉搜索树在 C 中实现关联数组 (int -> int)。但是,我当前的实现可靠地产生了一个段错误,我不太清楚为什么。如果问题很简单,我只是忽略了,我深表歉意。

代码:

#include <stdlib.h>
#include <stdio.h>

struct tree {
        int key;
        int value;
        struct tree *a;
        struct tree *b;
};

int summon (struct tree *t, int key) {
        if (t == NULL) {
                fprintf(stderr, "%s", "Key not in tree");
                exit(-1);
        } else {
                if (t -> key < key)
                        return summon(t -> a, key);
                else if (t -> key > key)
                        return summon(t -> b, key);
                else
                        return t -> value;
        }
}

struct tree _make (int key, int value) {
        struct tree ret;
        ret.key = key;
        ret.value = value;
        ret.a = ret.b = NULL;
        return ret;
}

void cast (struct tree *t, int key, int value) {
        if (key == t -> key) {
                t -> value = value;
        } else if (key > t -> key) {
                if (t -> a == NULL) {
                        struct tree n = _make(key, value);
                        t -> a = &n;
                } else {
                        cast(t -> a, key, value);
                }
        } else {
                if (t -> b == NULL) {
                        struct tree n = _make(key, value);
                        t -> b = &n;
                } else {
                        cast(t -> b, key, value);
                }
        }
}

int main (int argc, char **argv) {
        struct tree h = _make(5, 2);
        cast(&h, 16, 43);
        printf("%d", summon(&h, 16));
        return 0;
}

我在 Ubuntu 上使用 gcc; gdb 没有帮助。

在此,例如,

if (t -> a == NULL) {
    struct tree n = _make(key, value);
    t -> a = &n;
}

您正在将 指针 存储到具有自动存储持续时间的变量 t->a。但是 n 的生命周期在 } 处结束,并且 t->a 变成了 悬空指针 ;在任何上下文中使用此类指针都会导致未定义的行为。

需要为此任务使用动态内存分配(malloc 等)。