I have a problem with my function that does remove the node from a binary tree. Here a code:
void * remove_node(Node * removed_node) {
if (removed_node->left == NULL) {
Node * right_node = removed_node->right; void * node_value = removed_node->value;
free(removed_node); removed_node = right_node;
return node_value;
} else {
/* here a code for find the node with minimal key in a right subtree */
}
}
As you can see, a removed node will be freed and assign to the NULL-pointer. Also, I have a function for destroying an entire tree:
int namespace_destructor(Node * root) {
if (root == NULL) return 0;
else {
constant_destructor(root->value); // if the current node is a pointer to existed value don't free it
if (root->left != NULL) namespace_destructor(root->left);
if (root->right != NULL) namespace_destructor(root->right);
free(root);
}
}
Problem is here: when I'm calling the namespace_destructor
I've having SEGFAULT
, because I've already freed the memory for removed node. But why? At this line free(removed_node); removed_node = right_node;
I'm already set the NULL
pointer to removed_node (in my case right_node
is NULL, because removed node
is the last node of tree). If I do not freed the memory, a variable root
anyway is not equal to NULL
.
Here the Node
structure:
typedef struct Node {
int key;
void * value;
struct Node * left;
struct Node * right;
} Node;
Here a code where I'm trying to call these two functions:
if (returned_value->origin != NULL) remove_node(returned_value->origin);
namespace_destructor(local_namespace);
Thank you for yours attention.