开发者

Vector or element causing a segfault?

I am getting a segmentation fault in my program and gdb tells me it is in this function on the line of

parent->getChildren().push_back(temp);

in

void Tree::add(Position& value, Node*& parent) {
    Node* temp = new Node(value, parent);
    parent->getChildren().push开发者_C百科_back(temp);
}

I have added cout statements before that line and everything seems to be valid when the function is called. But I don't think my vector can be invalid? The vector declaration is here -

std::vector<Node*> children;

with getChildren() just returning std::vector&. Any help is appreciated.

Node constructor:

Tree::Node::Node(Position& v, Node*& p)
    : value(v), parent(p), gvalue(0), hvalue(0), fvalue(0) {} 


That can't be an "element problem" because you just push_back(Node*). That can't fail.

So I see 2 possible "vector problems":

  1. Problem with parent-> because parent is not allocated.
  2. Problem with getChildren(). because it returns a reference to non-existing vector.

Try to check both of them.


Add the line:

void Tree::add(Position& value, Node*& parent) 
{
    if (parent == NULL)
    {
        std::err << "Error Null parent. Aborting\n";
        exit(1);
    }
    Node* temp = new Node(value, parent);
    parent->getChildren().push_back(temp);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜