You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++创建类对象指针后触发段错误,附错误信息与代码片段求助

排查C++代码中的段错误问题

让我们一步步拆解你遇到的段错误问题,结合你的代码和错误信息来看,主要有几个关键问题需要修复:

1. 无限循环导致队列无法清空(最直接的段错误诱因)

你的while (!unvisited.empty())循环里,只通过unvisited.front()取出了队列头部的节点,但从来没有执行unvisited.pop()来移除这个节点。这会导致unvisited队列永远不为空,循环无限运行:

  • 不断创建新的Node对象(通过new Node(c+1))会耗尽内存,最终触发段错误;
  • 无限的输出和循环操作也会导致系统资源耗尽。

修复方法:在取出节点后立刻调用pop():

Node node = unvisited.front();
unvisited.pop(); // 必须添加这一行,否则队列永远不为空
std::cout << "Node, label:" << node.getLabel() << ",column index:" << node.getLabel() - 1 << std::endl;

2. 内存泄漏与不必要的动态内存分配

代码中Node * adj = new Node(c+1);然后node.addToAdjacenyList(*adj);的写法存在两个问题:

  • 动态分配的Node对象没有被delete,会持续泄漏内存,长期运行必然导致内存耗尽;
  • 如果addToAdjacenyList是存储Node值而非指针,完全不需要用new,直接构造临时对象即可。

修复方法:去掉动态分配,直接传入构造的对象:

// 替换原来的动态分配代码
Node adj(c+1);
adj.setPrev(node);
node.addToAdjacenyList(adj);

3. 潜在的空指针访问风险

如果Node类中的adjacency list没有在构造函数中初始化(比如getAdjacenyList()返回nullptr),那么node.getAdjacenyList()->size()这一行会直接触发段错误。

请确认Node类的构造函数中,是否正确初始化了邻接列表,比如:

class Node {
private:
    std::vector<Node> adjacencyList; // 直接用vector而非指针更安全
public:
    Node(int label) {
        // 其他初始化逻辑
    }
    std::vector<Node>* getAdjacenyList() {
        return &adjacencyList;
    }
};

4. 未明确的std::endl命名空间

你的代码中使用了endl但没有加std::前缀,而代码里明确使用了std::vector,说明你没有使用using namespace std;。这会导致编译错误,但如果编译器默认允许的话,也可能引发未定义行为,建议改为std::endl。

修复后的核心代码片段

void graph::shortest_path(std::vector<std::vector<int>> &_matrix) {
    //1) initialize not visited nodes
    int num_of_nodes = _matrix.size();
    std::queue<Node> unvisited;
    std::queue<Node> visited;
    for (int i = 0; i < num_of_nodes; i++) {
        unvisited.push(Node(i + 1));
    }
    //while unvisited is NOT empty
    while (!unvisited.empty()) {
        //2) pop/remove from unvisited & are there adjacent neighbors
        Node node = unvisited.front();
        unvisited.pop(); // 新增:移除队列头部节点
        std::cout << "Node, label:" << node.getLabel() << ",column index:" << node.getLabel() - 1 << std::endl;
        vector<int>& columnVector = _matrix[node.getLabel() - 1];
        //nodes integer label
        int label = 0;
        //loop add adjacency list * back pointers
        for (int c = 0; c < columnVector.size(); c++) {
            //if there are actual connections, then adjacency matrix value at C NOT equal INT_MAX
            if (columnVector[c] != INT_MAX) {
                //create a node & add to current nodes adjacency list
                Node adj(c+1);
                adj.setPrev(node);
                node.addToAdjacenyList(adj);
                //also set the prev reference
            }
        }//end loop add adjacency list * back pointers
        //3) for each node calculate the total weight or cost back to the start & select the min
        if (node.getAdjacenyList() != nullptr) { // 新增:空指针检查
            for (int i = 0; i < node.getAdjacenyList()->size(); i++) {
                std::cout << node.getAdjacenyList()->at(i).getLabel() << ",";
                ...
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者cyber101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:03:10