ianwt
ianwt

Reputation: 109

Calling member function via pointer C++, object is null?

I have a pointer to a ListNode object sum_ptr, which points to sum. When I call the append method via sum_ptr, I get a segfault. Looking at gdb, I am seeing that "this" is 0x0 in the call to append, which does not make sense. Does anyone know why the sum object would be null at the point at which the append method is called? Thank you!

  ListNode sum;
  ListNode* sum_ptr = ∑
  
  const ListNode* l1_ptr = &l1;
  const ListNode* l2_ptr = &l2;

  int c_over = 0;
  while(l1_ptr != nullptr && l2_ptr != nullptr){
    int temp_sum = l1_ptr->val + l2_ptr->val + c_over;
    temp_sum = temp_sum >= 10 ? temp_sum - 10 : temp_sum;
    c_over = temp_sum >= 10 ? 1 : 0;

    sum_ptr->append(temp_sum);
    sum_ptr = sum_ptr->next;
    
    l1_ptr = l1_ptr->next;
    l2_ptr = l2_ptr->next;
  }

Append method:

void ListNode::append(int v){
  if(this->val == INT_MIN){
    this->val = v;
  }
  else{
    ListNode *e = new ListNode();
    e->val = v; 
    ListNode* n = this;
    while(n->next != nullptr){
      n = n->next;
    }
    n->next = e;
  }
}

Upvotes: 0

Views: 75

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

The reason of the problem is the following.

You declared a node using the default constructor.

ListNode sum;

It seems that the default constructor sets the data member next to nullptr and the data member val to the value INT_MIN (that does not make a sense).

Then you are calling the member function append the first time using the pointer sum_ptr.

ListNode* sum_ptr = ∑
//...
sum_ptr->append(temp_sum); 

The member function append in this case just changes the data member val.

void ListNode::append(int v){
  if(this->val == INT_MIN){
    this->val = v;
  }
  //...

And then you are reassigning the pointer in the while loop

sum_ptr = sum_ptr->next;

So now the pointer sum_ptr has the value of the data member sum.next that is equal to nullptr. And you are using this null pointer in a next call of the member function append that results in undefined behavior.

Also pay attention to that for example this pair of statements

temp_sum = temp_sum >= 10 ? temp_sum - 10 : temp_sum;
c_over = temp_sum >= 10 ? 1 : 0;

does not make a sense because after execution of the first statement temp_sum is always less than 10. So the variable c_over always will be set to 0. You need at least to exchange these statements.

Upvotes: 1

Related Questions