分段故障二叉树

时间:2014-02-04 10:10:26

标签: c pointers

我正在尝试学习一些C,然后我开始实现二叉树。

我正在尝试的第一件事是插入树中。但是,我遇到了分段错误,我无法弄清楚原因。

当我尝试将*tree参数设置为具有传入值的新节点时,会发生分段错误。我首先尝试使用free(*tree)但这并没有真正帮助。

根据我的理解,我有一个指向我树的指针的指针。所以我应该更新指向的指针(如果这有意义吗?)。 createNode(val)返回指向节点的指针。所以我想我可以简单地用指针代替'pointee'。所以我有一个指向新指针的指针,该指针最初为NULL

我知道在这一点上我并没有真正了解指针是如何工作的,但这就是为什么我在努力......     #包括     #包括     #include

typedef struct node {
    int val;
    struct node * left;
    struct node * right;
}node;

node * createNode(int val)
{
    node * n = malloc(sizeof(node));
    n->val = val;
    n->left = NULL;
    n->right = NULL;

    return n;
}
node * createTree()
{
    node * root = malloc(sizeof(node));
    root->val = 12;
    root->left = createNode(10);
    root->right = createNode(14);

    root->left->left = createNode(8);
    root->left->right = createNode(9);

    root->right->left = createNode(13);
    root->right->right = createNode(16);

    return root;
}
void insertInTree(node ** tree, int val)
{
    printf("%i\n", (*tree)->val);

    if((*tree) == NULL)
    {
        free(*tree);
        *tree = createNode(val);
    }
    else
    {
        if((*tree)->val > val)
        {
            insertInTree(&(*tree)->left, val);
        }
        else
        {
            if((*tree)->val < val)
            {
                insertInTree(&(*tree)->right, val);
            }
        }
    }   
}

main()
{
   node * tree = createTree();
   insertInTree(&tree, 5);
   getchar();

}

1 个答案:

答案 0 :(得分:4)

insertInTree()

printf("%i\n", (*tree)->val);

在访问最后一个节点(NULL

后,您获得了一个SEGFAULT

调试器会告诉您:

david@debian:~$ gdb demo
GNU gdb (GDB) 7.4.1-debian
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/david/demo...done.
(gdb) run
Starting program: /home/david/demo 
12
10
8

Program received signal SIGSEGV, Segmentation fault.
0x00000000004006ea in insertInTree (tree=0x601078, val=5) at demo.c:36
36      printf("%i\n", (*tree)->val);