c ++难以捉摸的分段错误

Mat*_*att 2 c++ pointers class segmentation-fault

我正在处理这段代码,我不断收到分段错误.对于我的生活,我无法弄清楚为什么,我知道一个分段错误是当你尝试遵循空指针,但问题是,在我的代码"u-> previous"isnt null,也不是"u",我检查.如果我将while循环中的条件更改为(u!= NULL),它将在出现"u-> isGreen"之前迭代两次,再一次,我检查每次迭代以查看是否为null.

int extractOptimalPath() {
    Node *u = nodes[NUM_NODES - 1];

    int i = 0;
    while (u != NULL) {
        cout << i << endl;
        u->isGreen = true;
        u = u->previous;
        i++;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

"nodes"是指向实际Node对象的指针数组.我确信我的节点中存在"u-> previous","isGreen"初始化为false;

继承Node类,以防你想看到:

class Node {
    public: 
        GLfloat x, y, z;
        int numLinks;
        Node *link1;
        Node *link2;
        GLfloat distance;
        Node *previous;
        bool isGreen;

        Node(GLfloat x, GLfloat y, Node *link1, Node *link2);
        Node(GLfloat x, GLfloat y, Node *link1);
        Node();
        Node(GLfloat x, GLfloat y);
        ~Node();

        bool dijkstra(Node* graph[], Node *source, Node *target); //returns true if a path to target is found
        int dist(Node *n1, Node *n2);
        int extractOptimalPath(Node* graph[]);
};
Run Code Online (Sandbox Code Playgroud)

什么可能导致seg错误?

Pup*_*ppy 7

该错误不仅适用于空指针,而是指向任何无效指针的指针.这可以为null,但也可以是已释放的内存.