0

I'm learning C++ and I want to implement a simple linked list. Here is my code.

#include <vector>
#include <iostream>
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};
int main()
{
    ListNode start = ListNode(-1);
    ListNode *startptr = &start;
    for(int i=0;i<3;i++)
    {
        ListNode foo=ListNode(i);
        startptr->next = &foo;
        startptr = startptr->next;
    }
    
}

But after running the code, I find that something goes wrong. In the code

ListNode foo=ListNode(i)

foo always has the same address that the startptr cannot point to a new node. I switch to the debug mode, and get this picture:

enter image description here

It seems like there is only one foo, and each time I 'create' a new ListNode called foo, the last ListNode will be overwrite.

I used to work with Python, and I haven't met such kind of problem. It is really confusing to me.

3
  • 6
    I recommend learning from a C++ book. Programming experience in Python is a boon, but don't apply the Python object model onto C++ objects. Commented Jan 8, 2018 at 8:50
  • Story Teller's right here, you need to get a good book/tutorial to learn idiomatic C++ from. Commented Jan 8, 2018 at 8:51
  • 1
    Use dynamic memory allocation instead Commented Jan 8, 2018 at 8:52

1 Answer 1

4

With ListNode foo=ListNode(i); startptr->next = &foo;, you are referring to an object with automatic storage duration and block scope. Hence, object foo will be destroyed at the end of each loop cycle, and referring to it later on yields undefined behaviour.

The nodes of a linked list are often created with dynamic storage duration, i.e. with new. See the following adapted code illustrating this:

int main()
{
    ListNode *start = new ListNode(-1);
    ListNode *ptr = start;
    for(int i=0;i<3;i++)
    {
        ListNode *foo = new ListNode(i);
        ptr->next = foo;
        ptr = ptr->next;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Could you please modify the example or add a note about preferring smart pointers over raw pointers?

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.