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

213 Views Asked by At

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;
}
1

There are 1 best solutions below

0
Vlad from Moscow On BEST ANSWER

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;
};