Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading