启用g ++优化会导致分段错误

Yan*_*hao 1 c++ g++ c++11

我编译使用时,我的程序会出现分段错误:

g++ -std=c++11 iForest.cpp -o iForest -O2
Run Code Online (Sandbox Code Playgroud)

我已经读过这个帖子 - 打开g ++优化会导致段错误 - 我不明白,但我不认为我在那里遇到了同样的问题.我还检查了我的代码.我真的不知道哪里可能存在问题.请提供一些帮助.这是我的代码:

    #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;
}
Run Code Online (Sandbox Code Playgroud)

编译时没有生成段错误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
Run Code Online (Sandbox Code Playgroud)

M.M*_*M.M 7

root当您通过构造函数iTree(const string &fname){ readData(fname); }(在示例中执行)输入时,您的类包含未初始化的变量.那么你的析构函数就可以了delete root;

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

为了避免错误以后这将是很好的同时声明Node,并iTree作为不可复制和不可移动的,直到你准备实施的复制操作他们.由于三次违规规则,默认的复制/移动行为将导致内存错误.