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

C++调用inputtree构建树时程序异常终止,如何修复?

问题修复方案

核心问题

程序崩溃的根本原因是野指针访问:main函数中声明的tree<int>* sample;是未初始化的指针,指向内存中的随机地址,当inputtree函数尝试通过root->data或root->children访问该野指针的成员时,直接触发未定义行为,导致程序终止。

修复后的完整代码

#include <iostream>
#include <vector>
using namespace std;

template <typename t>
class tree{
public:
    t data;
    vector<tree<t>*> children;
    // 用初始化列表规范构造函数
    tree() : data() {}
    tree(t data) : data(data) {}
};

void inputtree(tree<int>* root){
    int size;
    cin >> size;
    for(int i=0; i<size; i++){
        int element;
        cin >> element;
        tree<int>* child = new tree<int>(element);
        root->children.push_back(child);
        inputtree(child); // 递归输入子节点数据
    }
}

int main(){
    // 初始化根节点,避免野指针
    int rootData;
    cout << "输入根节点数据: ";
    cin >> rootData;
    tree<int>* sample = new tree<int>(rootData);
    inputtree(sample);
    
    // 注意:后续需手动释放内存避免泄漏,或使用智能指针替代裸指针
    return 0;
}

关键修复点说明

  1. 初始化根指针:在main中通过new tree<int>(rootData)创建合法的根节点对象,让sample指向有效内存地址,彻底解决野指针问题。
  2. 调整输入逻辑:原代码中inputtree会重复覆盖根节点数据,现在改为创建根节点时直接传入初始数据,避免冗余输入。
  3. 规范构造函数:使用初始化列表初始化成员变量,符合C++编码规范。

额外优化建议

  • 使用智能指针管理内存:用std::unique_ptr替代裸指针,自动释放内存,避免手动管理时的泄漏风险:
    #include <iostream>
    #include <vector>
    #include <memory>
    
    template <typename t>
    class tree{
    public:
        t data;
        std::vector<std::unique_ptr<tree<t>>> children;
        tree() : data() {}
        tree(t data) : data(data) {}
    };
    
    void inputtree(std::unique_ptr<tree<int>>& root){
        int size;
        std::cin >> size;
        for(int i=0; i<size; i++){
            int element;
            std::cin >> element;
            auto child = std::make_unique<tree<int>>(element);
            root->children.push_back(std::move(child));
            inputtree(root->children[i]);
        }
    }
    
    int main(){
        int rootData;
        std::cout << "输入根节点数据: ";
        std::cin >> rootData;
        auto sample = std::make_unique<tree<int>>(rootData);
        inputtree(sample);
        return 0;
    }
    
  • 移除全局using namespace std;:项目代码中建议显式使用std::前缀,减少命名冲突风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:43:31