这是我构建二叉树的代码。从GDB调试消息,insert_tree()的递归调用适用于3次递归,然后*树指针指向无效的地址。请帮忙!
typedef struct _TNode{
int data;
struct _TNode *left;
struct _TNode *right;
}TNode;
void insert_tree(TNode **tree,TNode *node)
{
if(!(*tree)){
*tree=node;
return;
}
else if(node->data < (*tree)->data)
insert_tree(&(*tree)->left,node);
else if(node->data > (*tree)->data)
insert_tree(&(*tree)->right,node);
}
TNode *build_btree(TNode **tree,int num)
{
TNode *node;
int i;
for(i=0;i<num;i++){
node=(TNode *)malloc(sizeof(TNode));
node->left=NULL;
node->right=NULL;
node->data=rand();
insert_tree(tree,node);
}
return *tree;
}
int main(int argc,char **argv)
{
if(argc<2){
printf("Usage: ./command <number of nodes to insert>\n");
return -1;
}
TNode *root;
int node_num=atoi(argv[1]);
root=build_btree(&root,node_num);
return 0;
}
这是GDB调试消息。不明白为什么* tree指向无效地址。
Program received signal SIGSEGV, Segmentation fault.
0x000000000040064a in insert_tree (tree=0x7fffffffe7d5, node=0x602010)
at btree_height.c:9
9 else if(node->data < (*tree)->data)
(gdb) list
4 {
5 if(!(*tree)){
6 *tree=node;
7 return;
8 }
9 else if(node->data < (*tree)->data)
10 insert_tree(&(*tree)->left,node);
11 else if(node->data > (*tree)->data)
12 insert_tree(&(*tree)->right,node);
13 }
(gdb) print node->data
$1 = 1804289383
(gdb) print node
$2 = (TNode *) 0x602010
(gdb) print *tree
$3 = (TNode *) 0x6e69622f3d4c4c45
(gdb) backtrace
#0 0x000000000040064a in insert_tree (tree=0x7fffffffe7d5, node=0x602010)
at btree_height.c:9
#1 0x0000000000400699 in insert_tree (tree=0x7fffffffe580, node=0x602010)
at btree_height.c:12
#2 0x0000000000400699 in insert_tree (tree=0x7fffffffe480, node=0x602010)
at btree_height.c:12
#3 0x00000000004006f7 in build_btree (tree=0x7fffffffe480, num=10)
at btree_height.c:28
#4 0x000000000040082b in main (argc=2, argv=0x7fffffffe578) at btree_height.c:56
(gdb)
答案 0 :(得分:3)
将root
设置为NULL
会删除此处的段错误。
TNode *root = NULL;