Im working on this bit of code and I keep getting a segmentation fault. For the life of me I cant figure out why, I know a segmentation fault is when you try to follow a null pointer, but the thing is, in my code "u->previous" isnt null, neither is "u", I checked. If I change the condition in the while loop to (u != NULL), it will iterate twice before faulting on "u->isGreen", Once again, I checked every iteration to see if u was 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;
}
"nodes" is an array of pointers to actual Node objects. I know for sure that the "u->previous" exists in my nodes and "isGreen" is initialized to false;
Heres the Node class, in case you want to see that:
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[]);
};
What could be causing the seg fault?
That error isn't just for null pointers, it is a pointer that points to anything invalid. That can be null, but it can also be memory that was freed.
I don't see a copy constructor in Node, while I see pointers and a destructor. So you violated the Rule of Three.
As a result, if you accidently copy a Node, that copy's destructor will result in effects you see now.
Update: To quickly test for this, add a private copy constructor to your Node class, like this:
class Node {
...
private:
Node(const Node&);
};
If you get compiler errors now, you are making copies. The compiler will point you to the locations where that happens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With