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.

Community
  • 1
  • 1
Wubin
  • 141
  • 2
  • 11

1 Answers1

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;
    }
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58