简体   繁体   中英

Runtime error in Linked List :member access within null pointer of type 'ListNode'

I am given two non-empty linked lists representing two non-negative integers and i am trying to Add the two numbers and return the sum as a linked list. And i am getting an error which says

Char 18: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior

Why am i getting this array and How does i solve this?

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry=0,sum = 0;
        ListNode* res = new ListNode(0);
        while(l1->next !=NULL){
            sum = carry + l1->val + l2->val;
            if(sum>9)
                carry = 1;
            else
                carry = 0;
            
            res = res->next;
            
            res->val = sum;
        }
        return res;
        
    }
};

The error is showing in Line with code

         res->val = sum;

This code has many bugs first of all, you are not updating the value of l2 so ultimately you are trying to add all the values of l1 with the head->node of l2 which is absurd.

As for the error, its happening because you are creating a new node ListNode* res = new ListNode(0); So according to this a new node is created with name res and res->next will contain NULL , this I am guessing as per the constructor call for your ListNode class.

So w.r.t above statement res = res->next; Now res is pointing to NULL. Further res->val = sum; you are trying to access the value inside null thus giving you runtime error because you are trying to access something which is not assigned.

I would recommend you to first try simple problem ' Adding 1 to a given linked list '. As it can also generate carry when you add 1 to 999 and resulting linked list should be 1000.
It will give you a better understanding on how to tackle this type of problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM