(Pointer) can you tell me the difference in two blocks of code?

Hi I am learning c++ linked list data structure.
I am stuck in understanding difference of these two blocks of code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1.First
void addAtHead(int val)
 {
        SinglyListNode *cur = new SinglyListNode(val);
        cur->next= head;
        head = cur;
        return;
        
 }
2.Second
void addAtHead(int val)
 {
        SinglyListNode *cur = new SinglyListNode(val);
        cur= head;
        head = cur;
        return;
        
 }
    

For some reason, with the second block,the program get wrong answer.
Line 14 wipes out line 13 resulting in a memory leak.
The newly allocated node is lost.
Line 13: You initial 'cur' with some value.
Line 14: You immediately overwrite this value with the value of 'head'.
Line 15: You assign 'cur' to 'head', but 'cur' currently contains the value of 'head', so you are essentially assigning the value of 'head' to itself.

In other words, all you're left with is a memory leak, and nothing else is changed.

PS: The return statements at the end of a void function are not necessary.
Last edited on
Thank you so much for your replying,
I thought line 14 could mean make "cur" pointer point to what head pointer points to. Is that wrong?
You are correct, line 14 is making cur point to the same data that head is pointing to. But you don't want this. You want cur to point to the dynamic memory you just allocated on line 13. Otherwise, what was the point in calling 'new SinglyListnode(val)'?

Pointers can be confusing, so let us know if it's still not clear; maybe somebody can explain it in a different way.

But to restate it a slightly different way:
1
2
3
SinglyListNode *cur = new SinglyListNode(val);
cur = head;
head = cur;

Is doing essentially the same thing as:
1
2
cur = head;
head = cur;


which is essentially doing the same thing as:
1
2
head = head;


which is doing nothing.
Last edited on
When getting to grips with linked lists, I find it useful to physically draw the nodes on paper as squares with lines going between the squares representing the links. Then walk through the code as the computer would and add the squares and lines etc as per the code and mark what variable points to where.
Thank you so much all for very well written explanation. It makes much more sense ! very clear!!
Topic archived. No new replies allowed.