Reputation: 477
I am trying to make a binary search tree, but when I try to insert any value, or more precisely when a NULL pointer gets passed to the function, it just freezes for a little while and then it crashes. Here's the code:
void create(int co, struct node **leaf){
if(*leaf==0){
(*leaf)=malloc(sizeof(**leaf));
(*leaf)->val=co;
(*leaf)->left=0;
(*leaf)->right=0;
}
else if(co<(*leaf)->val){
create(co, &(*leaf)->left);
}
else if(co>=(*leaf)->val){
create(co, &(*leaf)->right);
}
}
I can't figure out why it does that. Can you explain?
EDIT: The first call of the function looks like this:
struct node *root;
root=0;
for(i=0;i<c;i++){
create(f[i], &root);
}
Where c is the number of elements in the array. And this is the definition of the struct:
struct node{
int val;
struct node *left;
struct node *right;
};
So the problem is not in the code I posted here, the entire code can be found here If I should just rewrite the whole question and just post the whole code here please saz so in the commnets, will try to rectify ASAP.
FOUND MY ANSWER
After I got it to actually get past create
safely, I was able to find the last one mistake that screwed up my program. It was *i++;
. Apparently ++ doesn't work well with values being pointed to. After I rewrote it to *i=*i+1;
it finally works, so I' like to thank all the people who helped me and ask one final question: What is the difference between *i++;
and *i=i+1;
?
Upvotes: 0
Views: 190
Reputation: 49373
I took your struct definition and insert function exactly as they were and took your other code and dumped into a main()
function as such:
int main()
{
struct node *root;
int i, c = 10;
root=0;
for(i=0;i<c;i++){
create(i, &root);
}
return 0;
}
Seems it works just fine. I also tried a number of different ordered elements:
int f[] = {6, 1, 9, 2, 0, 18, 2, -8, 10000, 5};
And again, no crashes and I get the correct ordering...
Did you verify that c
, which you use in the condition: i<c
has f[]
number of elements? You could remove the c
by just using: sizeof(f)/sizeof(int)
.
What input makes this function fail? What is the exact error message it fails with?
When you "walk" your tree, did you check for NULL before printing values?
After you posted the whole code, I can see it crashes here:
int *pole, i, count=3;
pole[0]=25; <----
You didn't give pole any memory, so you're deferencing an uninitialized pointer.
pole = malloc(3 * sizeof(int));
fixes that, but there's more.
Next you'll die here:
void getorder(struct node *leaf, int *f, int *i){
if(leaf->left!=NULL){
getorder(leaf->left, f, i);
}
f[*i]=leaf->val; <-- this will kill you
Because again, you don't give j
any memory:
int *j;
...
*j=0;
getorder(root, f, j);
Upvotes: 1
Reputation: 18348
There is nothing wrong with the code. Here you can see it running fine and achieving the desired results. Working on gcc 4.3.4 (C90/C99)
and on gcc 4.7.2
.
Upvotes: 1