Skip to content

C++ Reverse Linked List accepted despite null pointer dereference #6123

Description

@senthil-lakshmikanth

Bug description

I submitted the following C++ code on both NeetCode and LeetCode:

Code

class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        ListNode* prev = nullptr;
        ListNode* current = head;
        ListNode* next = current->next;    

        while(current != nullptr)
        {
            current->next = prev;
            prev = current;
            current = next;   
            next = current->next;         
        }

        return prev;
    }
};
  • NeetCode: Accepted — 33/33 test cases
Image
  • LeetCode: Runtime Error — UndefinedBehaviorSanitizer
Image

The issue

The issue is caused by accessing current -> next
Since current is nullptr, this is a null pointer dereference and causes undefined behavior.

ListNode* current = head;
ListNode* next = current->next;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions