Why it gives segmentation fault?
Because you free the memory pointed by *root
before you try to access the same memory in temp1->left
.
Let's look at things closely :-
temp1 = (*root)
temp1 now holds the same memory address as (*root), i.e. both are some numbers that point to the same address. For the sake of clarity, let's assume that number to be '6'. So, both of them point to the memory address '6'. Note, they are not equal to the value at that address, but are just pointing to that.
Now, free((*root));
tells the system that you are freeing the memory location pointed to by (*root), which in this case is 6. Once you free the memory, you lose access permission to that memory and next time you request it (through temp1->left
), you get the segmentation fault.
I hope that clarifies what is causing the segmentation fault.
A cursory glance tells me that you could fix this by freeing (*root) at the end. In fact, the recursive call would be clearer that way, since you can describe it through this pseudo-code :-
delete left subtree
delete right subtree
delete root
I will not delve into the correctness of the logic as it appears to be a homework problem, and it'd be advisable that you solve that part yourself.