Search code examples
c++linked-listsingly-linked-listundefined-behaviornull-pointer

Why am I getting an "a.exe has stopped working" error on Visual Studio Code for my linked list program?


I'm playing around with a linked list, and I'm getting an error when I try to print out the value of the tail and the address of the next value:

struct Node {
    int n;
    Node *next;
};

class LinkedList {
    public:
        Node *head = NULL;
        Node *tail = NULL;
};

int main() {
    LinkedList L;
    L.head = NULL;
    L.tail = NULL;

    Node *new_node = new Node();
    new_node->n = 1;
    new_node->next = NULL;
    
    L.tail->next = new_node;
    L.tail = new_node;

    cout << L.tail << endl;
    cout << L.tail->next << endl;
}

Solution

  • Consider these statements:

    L.tail = NULL;
    //...
    L.tail->next = new_node;
    

    You are trying to use a null pointer to access memory. That invokes undefined behavior.


    Also, these assignments:

    LinkedList L;
    L.head = NULL;
    L.tail = NULL;
    

    are redundant, due to the class's default initialization of its members:

    class LinkedList {
        public:
            Node *head = NULL;
            Node *tail = NULL;
    };