Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

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

Why does it show segmentation Fault for only 1 test case out of 15 test cases. The next and the head pointers are accessible, i didn't even alter any of the in-editable pointers.

Error - Program terminated with signal SIGSEGV, Segmentation fault. #0 0x0000000000401364 in compare_lists (head2=, head1=0x192f5b0) at 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;
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Before assigning a node to its next neighbor, you should check it for null.

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

Little update: That doesn't seem to be the problem, I thought you were checking temp and temp2 themselves for null in your loop condition. In that case, your code will crash if one of them is originally null. i.e. one list is empty.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...