member access within null pointer of type 'struct ListNode'

49,234

You only make sure that runner->next is not null, however after assignment

runner = runner->next->next;

runner can become null.

Share:
49,234
Dukakus17
Author by

Dukakus17

Updated on July 18, 2022

Comments

  • Dukakus17
    Dukakus17 almost 2 years
    struct ListNode {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(NULL) {}
    };
    
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            if(head == NULL) return false;
            ListNode* walker = head;
            ListNode* runner = head;
            while(runner->next != NULL && walker->next != NULL){
                walker = walker->next;
                runner = runner->next->next;
                if(walker == runner) return true;
            }
            return false;
        }
    };
    

    I was practicing an interview code which seemed to be pretty simple. I have to return a bool that determines whether or not the singly-linked list has a cycle. I made two pointers walker which moves 1 step and runner which moves 2 steps every iteration.

    But then this code gave me an error:

    Line 15: member access within null pointer of type 'struct ListNode'
    

    What causes that error?