c - 这种基本的二叉搜索树算法会导致段错误:11 error

标签 c segmentation-fault binary-search-tree

这个简单的二叉搜索树会导致段错误:11

我无法理解代码的哪一点造成了这个问题。

为什么会出现segmentation failure:11

递归binarySerach函数不会错,因为它来自教科书。

所以我认为我在定义树方面非常无知,可能是关于malloc的事情。

这样定义treePointer是否正确?

我完全被错误segmentation failure:11所诅咒。

我想知道这个错误何时发生。

附注抱歉我的英语不好。


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

typedef struct element
{
        int key;
} element;

typedef struct node *treePointer;
typedef struct node
{
        element data;
        treePointer leftChild;
        treePointer rightChild;
} node;

element* binarySearch(treePointer tree, int key);

int main(void)
{
        treePointer *a;

        for(int i = 0; i < 10; i++)
        {
                a[i] = malloc(sizeof(node));
                a[i] -> data.key = i * 10;

                a[i] -> leftChild = NULL;
                a[i] -> rightChild = NULL;

        }
        a[0] -> leftChild = a[1];
        a[0] -> rightChild = a[2];

        a[1] -> leftChild = a[3];
        a[1] -> rightChild = a[4];

        a[2] -> leftChild = a[5];
        a[2] -> rightChild = a[6];

        a[3] -> leftChild = a[7];
        a[3] -> rightChild = a[8];

        a[4] -> leftChild = a[9];


        element* A = binarySearch(a[0], 30);
        printf("%d\n", A -> key);

        for(int i = 0; i < 10; i++)
        {
                free(a[i]);
        }
}

element* binarySearch(treePointer tree, int key)
{
        if(!tree) return NULL;
        if(key == tree -> data.key) return &(tree -> data);
        if(key < tree -> data.key)
                return binarySearch(tree -> leftChild, key);
        return binarySearch(tree -> rightChild, key);

}

最佳答案

您还需要为a分配内存。将其声明更改为:

treePointer *a = malloc(10 * sizeof(treePointer));

并在最后调用free(a);。此外,它没有找到 key ,因此返回 NULL,这会导致 printf("%d\n", A->key); 出现未定义的行为。但那是因为你的 BST 设置不正确。根元素的键为 0,它的两个子元素的键为 1020,这不可能是正确的。

关于c - 这种基本的二叉搜索树算法会导致段错误:11 error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55917698/

相关文章:

c - 使用 scanf 接受字符串并使用 printf 显示它们

c - 我将 C 代码翻译成 CPU 指令是否正确?

c - 即使在整整两天后也完全看不出是什么导致了段错误

C++11:带有 std::thread 和 lambda 函数的段错误

c - 文件处理时我的二进制搜索树代码中的段错误

将字符串更改为帕斯卡大小写

在 c 中的两次执行之间故意更改随机内存位置

c - 有没有更好的方法来确保矩阵之外的元素不被访问?

java - 用java开发一个2-3搜索树

java - 二叉搜索树中的递归方法-java