shylonezeng
shylonezeng

Reputation: 26

Member value of Linklist changed unexpextedly


Member value of Linklist changed unexpextedly. When the program gets the definition of pointer of pointer(see codes I pasted below), member val of second element of l2 changed.After debugging, I got that "ListNode **tail;" use the same address as second element of l2. Please help me find out the probelm and tell Why?


Linklist struct as below:

struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
}

piece of problem code as below:

  ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
  ListNode *p1=l1;
  ListNode *p2=l2;

  ListNode *rst=new ListNode(-1);
  ListNode **tail;  /*accident happened after here*/
 *tail=rst;
     ...
  }

I can figure that tail not initialized result in this bug. But I'v no idea what is go on.

Upvotes: 0

Views: 34

Answers (1)

R Sahu
R Sahu

Reputation: 206737

The problem with the following lines of code

ListNode **tail;  /*accident happened after here*/
*tail=rst;

is that you have not allocated memory for tail yet you are dereferencing it.

Perhaps you meant to use:

ListNode **tail = &rst;

Upvotes: 1

Related Questions