Mayukh Sarkar
Mayukh Sarkar

Reputation: 2625

Unusual Segmentation Fault

I was trying to delete alternate nodes in a linklist. I observed a strange behaviour.

void delete_alternate_node_LinkedList(Node *head) {
    Node *prev = head;
    Node *curr = head->next;
    while (prev != NULL and curr != NULL) {
        prev->next = curr->next;
        free(curr);
        prev = prev->next;
        if (prev != NULL) {
            curr = prev->next;
        }
    }
}

This code works fine except the head being nullptr when I use free to delicate or intentionally keep a memory leak but if I change the line free(curr) with delete curr, I get a segmentation fault.

Can anyone explain me the reason?

Here are the boilerplate codes

class Node {
public:
    int data;
    Node * next;
    Node(int data){
        this -> data = data;
        this -> next = NULL;
    }

    ~Node() {
        if(next) {
            delete next;
        }
    }
};
Node* takeinput() {
    int data;
    cin >> data;
    Node *head = NULL, *tail = NULL;
    while(data != -1){
        Node *newNode = new Node(data);
        if(head == NULL) {
            head = newNode;
            tail = newNode;
        }
        else{
            tail -> next = newNode;
            tail = newNode;
        }
        cin >> data;
    }
    return head;
}

void print(Node *head) {
    Node *temp = head;
    while(temp != NULL) {
        cout << temp -> data << " ";
        temp = temp -> next;
    }
    cout << endl;
}

Upvotes: 0

Views: 76

Answers (1)

fadedreamz
fadedreamz

Reputation: 1156

Your destructor has a problem Let's assume A->B->C->D->nullptr Now when you delete B it invokes destructor (if you use free it won't). it will delete recursively C (which in turn delete D) and ..... till the end so in next iteration you are holding on to a dangling pointer (C) and getting the segfault when you are trying to derefence it.

Upvotes: 3

Related Questions