antelemon
antelemon

Reputation: 55

Removing a Node in C

so I'm trying to write a method that deletes a node and all nodes attached to it, but I'm confused on what to do. I know the free method releases the memory used, and when I created the node, I used malloc. I'm unsure why free isn't removing the node and what should I do instead.

struct node {
        char *data;
        struct node *left;
        struct node *right;
}*child = NULL;

    void delete(node* root){
        char array[13];
        node *toDelete;
        //takes in name of node to be deleted
        //scan method to find the node to delete and deletes all of the children of the node first before deleting
        printf ("Please specify a name to delete\n");
        scanf("%s", array);
        toDelete = scan(root, array); //return which node to delete
        removeChild(&toDelete);  //helper method here to go through and delete each children
        if(toDelete == NULL) {
                printf("ERROR -- Node does not exist");
        }
}


void removeChild(node **trash){
        if((*trash)->left == NULL && (*trash)->right == NULL) { //no parents
                free(trash);
                *trash = NULL;
        }
        else if((*trash)->left == NULL && (*trash)->right != NULL) { //have mother
                removeChild((*trash)->right);
        }
        else if((*trash)->left != NULL && (*trash)->right == NULL) { //have father
                removeChild((*trash)->left);
        } else{  //have both
                removeChild((*trash)->left);
                removeChild((*trash)->right);
        }
}

Upvotes: 3

Views: 83

Answers (1)

wallyk
wallyk

Reputation: 57784

I didn't look thoroughly at your code, but I saw this which doesn't do what you think it does:

void removeChild(node * trash){
    if(trash->left == NULL && trash->right == NULL) { //no parents
            free(trash);
            trash = NULL;
    }
 ...

The last statement which intends to clear the pointer only does that for the parameter. The caller's pointer (which is passed to removeChild()) does not have its pointer NULLed. That is because parameters passed to a function are copied. They are not passed by reference.

Presumably other code could depend on the pointer being cleared, and so this would not satisfy it.

Upvotes: 4

Related Questions