My program gives segmentation fault when I compile using:
g++ -std=c++11 iForest.cpp -o iForest -O2
I have read this thread --Turning on g++ optimization causes segfault - I don't get it, but I don't think I made the same problem there. I also checked my code. I don't really see where may exist a problem. Please provide some help. Here is my code:
#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;
}
There is no segfault generated when I compile with g++ -std=c++11 iForest.cpp -o iForest
. There is also no segfault generated if I don't print. But I don't think there is any error in my print() function.
Here is the "data.dat" I used if you want to run it:
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