0

我遇到了分段错误。我相信这与我如何进行比较有关。我很困惑,对 C++ 很陌生。

最后一行pq.pop()是进入堆栈跟踪并导致失败的调用。执行 ./a.out 时不打印任何内容

class Node {
    public:

    Node() {}

    Node(int b) {
        bound = b;
    }

    Node(int b, Node * p) {
        bound = b;
        parent = p;
    }

    void addChild(Node& n) {
        n.parent = this;    
    }

    Node * parent;

    int bound;
};



class CompareNode {

public:
    bool operator()(Node *n, Node *o)
    {
        cout << "Comparing " << n->bound;
        cout << " to " << o-> bound <<endl;
        return n->bound > o->bound; 
    }
};


在主要


std::priority_queue<Node*, vector<Node*>, CompareNode> pq;
Node* root = new Node();
Node* node;
for(int i = 0; i < n; i++) {
  node = new Node(matrix[0][i], root);
  pq.push(node);
}

pq.pop();


广发银行


(gdb) run
Program received signal SIGSEGV, Segmentation fault.
0x00000000004027e7 in void std::__pop_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode) ()
(gdb) backtrace
#0  0x00000000004027e7 in void std::__pop_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode) ()
#1  0x0000000000401e13 in void std::pop_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, CompareNode)
    ()
#2  0x0000000000401a11 in std::priority_queue<Node*, std::vector<Node*, std::allocator<Node*> >, CompareNode>::pop() ()
#3  0x00000000004015dc in main ()
4

1 回答 1

1

C++ 通常不会为您检查必要的先决条件。如果你调用pop一个空结构,结果很可能是崩溃。所以这是我要看的第一个地方。

您可能会在 GCC 中使用-D_GLIBCXX_DEBUG. 它添加了边界检查、迭代器验证等,无论如何它都是一套很好的训练轮。

于 2013-03-07T04:44:35.420 回答