I want to insert data to the tree using this function:
struct treeNode{
data* val;
struct treeNode *left, *right, *parent;
};
void insert(data *d, struct treeNode **leaf, struct treeNode **leaf_par)
{
if( *leaf == 0 )
{
*leaf = (struct treeNode*) malloc( sizeof( struct treeNode ) );
(*leaf)->val = d;
/* initialize the children to null */
(*leaf)->left = 0;
(*leaf)->right = 0;
/* initialize the parent */
(*leaf)->parent = *leaf_par; //here I receive segmentation fault
}
else if(strcmp(d->name, (*leaf)->val->name) < 0)
{
insert( d, &(*leaf)->left, &(*leaf) );
}
else if(strcmp(d->name, (*leaf)->val->name) > 0)
{
insert( d, &(*leaf)->right, &(*leaf) );
}
}
In main I have:
struct treeNode *root = NULL;
data d1 = {"Smith"};
insert(&d1, &root, NULL);
Segmentation fault is there:
(*leaf)->parent = *leaf_par;
At first time *leaf_par is NULL and I don't know why it's not running correctly. How should I fix my insert function? Without "parent" pointer it's easy, but I have to do that with "parent" and it's not working.
You are trying to dereference NULL; don't do that.
A simple fix for your first insert is:
insert(&d1, &root, &root);
Deeper inserts into the recursion will fix the pointer.
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.