简体   繁体   中英

This basic binary search tree algorithm causes segmentation fault:11 error

This simple binary search tree causes segmentation fault:11 .

I can't understand which point of the code is making this problem.

Why this segmentation fault:11 is occuring?

The recursive binarySerach function can't be wrong because it is from textbook.

So I think I have a significant ignorance in defining a tree maybe something about malloc .

Is it right to define treePointer like that??

I'm totally cursed with the error segmentation fault:11 .

I want to know when this error occurs.

PS Sorry for my poor english.


#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);

}

You need to allocate memory for a , too. Change its declaration to:

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

And call free(a); at the end. Also, it's not finding the key, so it returns NULL which causes undefined behavior on printf("%d\\n", A->key); . But that's because your BST isn't set up correctly. The root element has key 0 and its two children have the keys 10 and 20 , that can't be right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM