【问题标题】:This basic binary search tree algorithm causes segmentation fault:11 error这种基本的二叉搜索树算法会导致分段错误:11 错误
【发布时间】:2019-04-30 09:17:52
【问题描述】:

这个简单的二叉搜索树导致segmentation fault:11

我不明白代码的哪一点造成了这个问题。

为什么会出现这个segmentation fault:11

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

所以我认为我在定义一棵树方面非常无知,可能与malloc 有关。

这样定义treePointer对吗??

我完全被错误 segmentation fault: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 的各个元素分配空间,但从不为数组a 本身分配空间。 a = malloc(10 * sizeof *a) 或类似的应该这样做。
  • a 指向哪里?

标签: c segmentation-fault binary-search-tree


【解决方案1】:

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

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

最后拨打free(a);。此外,它没有找到密钥,因此它返回NULL,这会导致printf("%d\n", A-&gt;key); 出现未定义的行为。但那是因为您的 BST 设置不正确。根元素有键0,它的两个子元素有键1020,这是不对的。

【讨论】:

  • 我更改了mallocpart 并修复了我的 BST 以包含正确的值以及 BST 的定义。但这仍然有相同的segmentation fault:11 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多