c++ elusive segmentation fault
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 开发者_如何学JAVA"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.
You don't need to have a NULL pointer to have a Segmentation Fault, it happens every time you access memory out of your allowed scope. Check the thread What is a segmentation fault?.
Your code isn't sufficient to say what causes a segfault. Most likely u->previous
in one of your nodes points to some more or less random place in memory, but it's just a guess.
My guess is that in your constructor of a Node object, the previous pointer is never set to NULL at any point. You should have a point when previous is set to NULL (in your actual code, don't assume the code does this for you automatically). Also, as a tip, try using gdb to step through your code. Another tip, valgrind is usually used to consult memory leaks, but I've used it to successfully pinpoint segfaults as well.
精彩评论