0

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.

Evgeniy
  • 303
  • 2
  • 9
  • Please show some code that actually calls those two functions. That's most likely where what you expect doesn't happen. – aschepler Apr 16 '20 at 21:47
  • Yes, because I need to get the value of removed node. Maybe my function should be named like `extracting_node_value`. – Evgeniy Apr 16 '20 at 21:47
  • `removed_node` is **local** to the function. Changing it does not change the caller's variable. To change the caller's value a `Node **` needs to be passed in and set with `*removed_node = NULL`. – kaylum Apr 16 '20 at 21:50
  • Added the part of code where I'm trying to call these functions – Evgeniy Apr 16 '20 at 21:51
  • @kaylum can you write an example please? – Evgeniy Apr 16 '20 at 21:53
  • 1
    This type of question is asked many times a day. Please check the linked posts. – kaylum Apr 16 '20 at 21:54

0 Answers0