Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

member access within null pointer of type 'struct ListNode'

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?

like image 534
Dukakus17 Avatar asked Jun 24 '17 07:06

Dukakus17


1 Answers

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

runner = runner->next->next;

runner can become null.

like image 129
user7860670 Avatar answered Oct 30 '22 09:10

user7860670