Runtime Error line number is wrong on C#

Running following code on https://leetcode.com/problems/palindrome-linked-list/ problem would result in

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public bool IsPalindrome(ListNode head) {
        
        ListNode slow = head;
        ListNode fast = head;
        Stack<ListNode> stack = new Stack<ListNode>();
        while (fast != null)
        {
            stack.Push(slow);
            slow = slow.next;
            fast = fast?.next?.next;
        }
        
        while (stack.Count > 0)
        {
            var pop = stack.Pop();
            if (pop.val != slow.val)
            {
                return false;
            }
            slow = slow?.next;
        }
        
        return true;
        
        
    }
}

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
Line 18: Solution.IsPalindrome(ListNode head) in Solution.cs
Line 33: Driver.Main(String[] args) in Driver.cs

Line 18 refers to the first while loop and it is not possible to have NullReferenceException for comparing object to null with != directly.
The actual exception occurs inside second loop if you run the exact same code with same SDK (C# NET 5) on Visual Studio Code.

if (pop.val != slow.val)

slow is actually null in this case. Changing the line to if (slow != null && pop.val != slow.val) prevents further NullReferenceException.

This Runtime Exception is clearly referencing a wrong line and if this info is inaccurate, this is actually worse than not having the line number.

Comments (0)