Memeory allocation

The codes below is to create a single linked list from an array input.
The first block of code does not work.
The second one works.

I just need to confirm whether my understanding is right.
Is that the first one creates and overwrite Node repeatedly in stack, so it caused problems?
The second one explicitly allocate Node's memory dynamically in heap avoiding overwriting issues, so it works?

Thanks,
L

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    ListNode* createLink(int array[],int n)
    {
        ListNode *currPtr,*root;
        ListNode dummy(0);
        currPtr=&dummy;
        root=&dummy;
        
        for (int i=0;i<=n-1;i++)
        {
            //ListNode *t=new ListNode((array[i]));
            //currPtr->next=t;
            ListNode Node(array[i]);
            currPtr->next=&Node;
            currPtr=currPtr->next;
        }
        return root->next;
    }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    ListNode* createLink(int array[],int n)
    {
        ListNode *currPtr,*root;
        ListNode dummy(0);
        currPtr=&dummy;
        root=&dummy;
        
        for (int i=0;i<=n-1;i++)
        {
            ListNode *t=new ListNode((array[i]));
            currPtr->next=t;
            //ListNode Node(array[i]);
            //currPtr->next=&Node;
            currPtr=currPtr->next;
        }
        return root->next;
    }
Is that the first one creates and overwrite Node repeatedly in stack, so it caused problems?
The first problem:

Line 13 assigns the pointer to the same object on the stack (each iteration the content will change). This might lead to a crash because of next doesn't make sense.

The second problem:

The object Node will become invalid after the loop ends und will be overwritten by other data on the stack. That will cause undefined behavior and will likely lead to crash [some time later].
Not really, the problem has more to do with loss-of-scope and the heap being persistent.

Edit: not a response to coder777, but to original question.
Last edited on
Thank you, both.
Topic archived. No new replies allowed.