0

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;
}
4
  • 1
    🔎🐞Did run your code in a debugger to see where that error occurs, then run it again with a breakpoint near that failure so you can step carefully ahead and watch what happens leading up to that point? Commented Feb 27, 2023 at 22:24
  • PSA: In C++ use nullptr in preference to C's typeless NULL. Commented Feb 27, 2023 at 22:24
  • L.tail->next is set null, so you're asking it to print an invalid Node pointer. Commented Feb 27, 2023 at 22:25
  • 1
    L.tail->next = new_node; is dereferencing a null pointer. I would expect this to go splat. Commented Feb 27, 2023 at 22:26

1 Answer 1

3

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;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.