运行时期间不一致的分段错误

时间:2016-09-06 17:34:48

标签: c++

我目前正在Project Euler #9进行刺戳并遇到分段错误。这些段错误只发生在我运行程序的第3到第4次。有人可以解释为什么会出现这种情况,更重要的是,为什么每次都不会出现段错误(或工作)?

我已经将段错误指向第二个while循环的开头,但仍然无法确定根本原因。

#include <iostream>
#include "LinkedList.h"

using namespace std;

int main(){
    int square, sum, answer = -1;
    int start = 1;

    LinkedList tripletChoices;    

    while (square<=1000){
        //create new node
        node * factor = new node;
        factor->root = start;
        square = start*start;
        factor->square = square;

        //insert into list
        if (square<=1000) tripletChoices.insertNode(factor);

        start++;
    }

    node * a_factor = tripletChoices.head;

    /** segfaults just after this ***********************/
    cout<<"before segfault" << endl;

    while(a_factor->next!=NULL){

        cout<<"after segfault" << endl;

        node * b_factor = a_factor->next;

        while(b_factor->next!=NULL){
            sum = a_factor->square + b_factor->square;

            cout<<"A: " << a_factor->square << " B: " << b_factor->square<< " sum:" << sum <<endl;

            node * c_factor = tripletChoices.head;

            while(c_factor->next!=NULL){

                if (sum == c_factor->square){
                    if ((a_factor->root + b_factor->root + c_factor->root)==1000){
                        answer = a_factor->root * b_factor->root * c_factor->root;
                        break;
                    }
                }

                c_factor = c_factor->next;
            }

            b_factor = b_factor->next;
        }

        a_factor = a_factor->next;
    }

    cout<<"Answer: " << answer << endl;
}

我的其余代码(如果相关):

LinkedList.h

#ifndef LinkedList_h
#define LinkedList_h

struct node{
    int root;
    int square;
    node *next;
};

class LinkedList{
    public: 
        node * head;
        int listLength;

        //default constructor creates head node
        LinkedList();

        //setter method
        bool insertNode(node * newNode);

        //destructor de-allocates memory used by the list
        ~LinkedList();
};

#endif

LinkedList.cpp

#include "LinkedList.h"
#include <iostream>

//Default Constructor - initilizes list with head node
LinkedList::LinkedList(){
    head = NULL;
    listLength = 0;
}

// setter method for inserting a new node
// inserts new node at the head of the list
bool LinkedList::insertNode(node * newNode){
    newNode->next = head;
    head = newNode;
    listLength++;
    return true;
}

//Destructor de-allocates memory used by list
LinkedList::~LinkedList(){
    node * p = head;
    node * q = head;

    while(q){
        p = q;
        q = p->next;
        if (q) delete p;
    }
}

1 个答案:

答案 0 :(得分:2)

由于访问未初始化的本地变量

而导致未定义的行为

在进入square循环之前,您正在访问未初始化的变量 while,因此它可能会也可能不会进入while循环。所以tripletChoices.head可能是也可能不是非空的,因为您无法确定是否会发生任何插入!

因此,取消引用nulla_factorwhile(a_factor->next!=NULL)会导致SegFault。