c++ - 开启g++优化导致segmentation fault

标签 c++ c++11 g++

我的程序在编译时出现段错误:

g++ -std=c++11 iForest.cpp -o iForest -O2

我已阅读此主题 -- Turning on g++ optimization causes segfault - I don't get it ,但我不认为我在那里遇到了同样的问题。我也检查了我的代码。我真的看不出哪里可能存在问题。请提供一些帮助。这是我的代码:

    #include <bits/stdc++.h>
using namespace std;

class iTree{
public:
    iTree(): root(NULL) {}
    iTree(const vector<double>& _items): items(_items){}
    iTree(const string &fname){ readData(fname); }
    ~iTree(){delete root;}

    void print(){
        for(int i = 0; i < np; ++i){
            for(int j = 0; j < nd; ++j){
                cout << items[i*nd + j] << " ";
            }
            cout << endl;
        }
    }

private:
    int height, np, nd; //np: # of points, nd: # of dimensions of a point
    vector<double> items;   // items.size() = np*nd;
    struct Node{
        double val;
        Node *left, *right;
        int attri;  // index of the attribute we pick

        Node(): val(0.0), left(NULL), right(NULL), attri(-1) {}
        ~Node(){ delete left; delete right;}
    } *root;

    void readData(const string &fname){
        ifstream ifs(fname);
        ifs >> np >> nd;

        items.resize(np*nd, 0.0);
        for(int i = 0; i < np*nd; ++i)  ifs >> items[i];
        ifs.close();
    }
};

int main(){
    iTree forest("data.dat");
    forest.print();
    return 0;
}

当我用 g++ -std=c++11 iForest.cpp -o iForest 编译时没有产生段错误。如果我不打印,也不会生成段错误。但我认为我的 print() 函数没有任何错误。

如果你想运行它,这里是我使用的“data.dat”:

10 5
509304 9 0 2 1.0
509305 9 0 2 0.0
509306 9 0 2 0.0
509307 9 0 2 0.0
509308 9 0 2 0.0
509309 9 0 2 0.0
509310 9 0 2 0.0
509311 9 0 2 0.0
509312 9 0 2 0.0
509313 9 0 2 0.0

最佳答案

你的类包含未初始化的变量root,当你通过构造函数输入时iTree(const string &fname){ readData(fname); } (你在你的例子中所做的)。然后你的析构函数执行 delete root;

要解决此问题,您可以初始化 root,最简单的方法是在其声明中将 {} 放在 ; 之前。

为了避免以后出现错误,最好将 NodeiTree 都声明为不可复制和不可移动,直到您准备好实现复制操作他们。由于 rule of three,默认的复制/移动行为将导致内存错误违规。

关于c++ - 开启g++优化导致segmentation fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36152109/

相关文章:

c++ - 为什么这个函数模板调用有效?

c++ - 没有匹配的函数可以调用

c++ - 使用 g++ 时使用 extern "C"{ 对 C++ 代码的影响

c++ - 与自定义对象一起使用 accumulate

c++ - Lib OPAL编译错误

c++ - 编译大型头文件 C++

c++ - 由于无效写入导致的段错误

c++ - 对可变参数模板函数的误解

c++ - 如何将此动态链接库链接到程序?

c++ - 在可执行文件的资源中,如何找到默认图标?