I'm trying to learn some C and I started by implementing a binary tree.
The first thing I'm trying is to insert into the tree. However, I'm getting a segmentation fault and I can't figure out why.
The segmentation fault happens when I try to set the *tree parameter to a new node with the passed in value. I tried using free(*tree) first but that doesn't really help.
From what I understand I have a pointer to the pointer of my tree. So I should update the pointer that is being pointed to (if this makes sense?). createNode(val) returns a pointer to a node. So I figure I can simply put that pointer in place of the 'pointee'. So I have a pointer to a new pointer, which was intially NULL.
I'm aware that I don't really get how pointers really work at this point, but that's why I'm trying.. #include #include #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();
}
root->left->left = createNode(8); root->left->right = createNode(9);Structure of the tree is not correct.freeif a node is NULL (if ((*tree) == NULL) { free(*tree);? There's no pointfreeingNULLs is legal, but it has no effect.freecall has no point. If it's not optimized away, all it does is add pointless function calls