为什么它给出了 Segmentation Fault 错误,但仅针对某些代码运行(或者我们可以说某些输入情况)?

Why it gives an error of Segmentation Fault but for only some runs of code(or we can say for some input cases)?

为什么在 15 个测试用例中只有 1 个测试用例显示分段错误。 next 和 head 指针是可以访问的,我什至没有改变任何不可编辑的指针。

错误 - 程序因信号 SIGSEGV 终止,分段错误。 #0 0x0000000000401364 compare_lists(head2=, head1=0x192f5b0) 在 Solution.cpp:70 line 70 while(temp->next != nullptr && temp2->next != nullptr){

bool compare_lists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2)
{
    SinglyLinkedListNode* temp = head1;
    SinglyLinkedListNode* temp2 = head2;
    bool abc;
    int i1 = 0;
    int i2 = 0;
    while (temp->next != nullptr && temp2->next != nullptr) {
        if (temp->data == temp2->data && i1 == i2) {
            ++i1;
            ++i2;
            abc = true;
            temp = temp->next;
            temp2 = temp2->next;
        }
        else {
            abc = false;
            temp = temp->next;
            temp2 = temp2->next;
        }
    }
    return abc;
}

在将节点分配给它的 next 邻居之前,您应该检查它是否为空。

if (temp->next != nullptr)
    temp = temp->next; 
if (temp2->next != nullptr) 
    temp2 = temp2->next;

小更新:这似乎不是问题所在,我以为您是在检查 temptemp2 自己在循环条件中是否为 null。在这种情况下,如果其中之一最初为 null,您的代码将崩溃。即一个列表是空的。

如果任何输入列表的元素少于两个,则您的函数具有未定义的行为。
在其他情况下,其结果仅取决于列表的 k:th 元素,其中 k+1 是较短列表的长度。
您也不需要计算元素;如果您到达了一个列表的末尾,但还没有到达另一个列表的末尾,则它们的长度不等。

请注意,当且仅当您到达两个列表的末尾且未遇到不同元素时,这两个列表才相等。

更简短的定义:

bool equal_lists(const SinglyLinkedListNode* head1, const SinglyLinkedListNode* head2)
{
    while (head1 != nullptr && head2 != nullptr) {
        if (head1->data != head2->data) {
            break;
        }
        head1 = head1->next;
        head2 = head2->next;
    }
    return head1 == nullptr && head2 == nullptr;
}