Runtime error while recursively calling a function with a double pointer as its default argument in c++

0

What I am trying to do:

I am trying to delete a node in a binary search tree. But before deleting the node we first have to search if the node exists and that I am checking in my search function which returns the address of the node where the match is found.

What is the problem:

After execution, the program throws an exception: Process returned -1073741819 (0xC0000005) And I believe the problem is with the statement (*parent) = root;But I don't know why it does so. And how to fix it.

My code:

Struct Defined As:

struct tree{
    int data;
    struct tree *left, *right;
};

Search function:

tree * search(tree *root, int value, tree **parent = NULL){

    tree * target = NULL;
    if (!root) return root;
    if (root->data == value) return root;
    if (value < root->data){
        // This returns the matched node
        target = search(root->left, value);
        // and this stores the parent of the matched node
        if (root->left->data == value)
            (*parent) = root;
    } else {
        target = search(root->right, value);
        if (root->right->data == value)
            (*parent) = root;
    }
    return target;
}

Delete function:

void del(tree *root, int value){
    tree * parent = NULL;
    if (!root) return;
    tree *target = search(root, value, &parent);
    // Deletion logic goes here
}
c++
recursion
asked on Stack Overflow Jul 11, 2018 by Ahtisham

1 Answer

1

The simple reason is that *parent=... is an assignment. That requires that parent is a valid (non-null) pointer. Yet you use nullptr as the default value of parent.

You'll need to fix the design of this function. This is not the only flaw.

answered on Stack Overflow Jul 11, 2018 by MSalters

User contributions licensed under CC BY-SA 3.0