Whi*_*zil 0 c++ if-statement segmentation-fault
我遇到了一个相当混乱的问题.看起来我程序中的IF语句导致了分段错误.
我正在使用外部库,并在IF语句中调用外部库中的代码,因此我无法提供这些函数的完整代码,因为我也没有.
会发生什么的基本例子.所以这个例子引起了我的兴趣Segmentation fault.
IRank *rank;
//Generating wavelet tree from BWT with sdsl library
if(true) {
std::cout << "I am in IF" << endl; // this gets printed on the screen
wt_huff<> wt; // right after that - segm fault
construct_im(wt, BWT, 1);
WTRank wtrank(&wt);
rank = &wtrank;
}
Run Code Online (Sandbox Code Playgroud)
但是,同样的例子,但没有IF,当我评论它时,不会导致Segmentation fault并正常执行.
IRank *rank;
//Generating wavelet tree from BWT with sdsl library
//if(true) {
std::cout << "I am in IF" << endl; // again this gets printed
wt_huff<> wt; // no segmentation error this time
construct_im(wt, BWT, 1);
WTRank wtrank(&wt);
rank = &wtrank;
//}
Run Code Online (Sandbox Code Playgroud)
原始示例:
// // Decide what rank function to use
IRank *rank;
if(m_wt) {
// Multiary Wavelet Tree rank function :: student implementation
mwt::node *m_wtree = mwt::generateMultiaryWT(BWT, ary);
MultiWTRank m_wt_rank(m_wtree, ary);
rank = &m_wt_rank;
} else if(b_wt) {
// Binary Wavelet Tree rank function :: SDSL implementation
wt_huff<> b_wtree;
construct_im(b_wtree, BWT, 1);
WTRank b_wt_rank(&b_wtree);
rank = &b_wt_rank;
} else if(non_wt) {
// Implementation of rank function not using Wavelet Tree
LinRank lin_rank(BWT);
rank = &lin_rank;
} else {
// should not happen
}
//...
run(rank);
Run Code Online (Sandbox Code Playgroud)
这里发生了什么,它是如此令人困惑?
编辑:从此片段调用其他代码的示例
#include "IRank.h"
#include "mwt.h"
class MultiWTRank : public IRank {
private:
mwt::node *wt;
int n_ary;
public:
MultiWTRank(mwt::node *root, int ary) {
wt = root;
n_ary = ary;
}
~MultiWTRank() {
}
index_type rank(index_type index, symbol_type symbol);
};
Run Code Online (Sandbox Code Playgroud)
所以这是在第一个IF中构建的.
EDIT2:提供一个代码,生成一个指向树的指针,可能会导致问题
class mwt {
public:
// Structure of a MW tree node
typedef struct node {
vector<int> data;
vector<node*> next;
} node;
// ...
static node* generateMultiaryWT(string input, int ary) {
//...
return root;
}
Run Code Online (Sandbox Code Playgroud)
节点创建如下:
static node* InitRoot(int ary){
node *root = new node;
for(int iter = 0; iter < ary; iter++){
root->next.push_back(NULL);
}
return root;
}
Run Code Online (Sandbox Code Playgroud)