【发布时间】: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