在我的trie实现中出现分段错误

Getting segmentation fault in my trie implementation

本文关键字:分段 错误 我的 trie 实现      更新时间:2023-10-16

我为trie实现编写了一个C++程序。但它在获取输入string后显示分段错误(此处称为elem(

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct trie {
char val;
vector<struct trie*> children;
trie(char c){ 
val = c; 
}
struct trie* add(char c){ 
struct trie* node = new struct trie(c);
children.push_back(node);
return node;
}
struct trie* find(char c){
for (auto child: children)
if(child->val == c) return child;
return nullptr;
}
};
int present(struct trie* root, string& elem, int pos) {
if(pos == elem.size()) return 1;
root = root->find(elem[pos]);
if(root == nullptr) return 0;
return present(root, elem, ++pos);
}
int main() {
int testcase;
cin >> testcase;
int elements;
string elem;
while(testcase--){
cin >> elements;
struct trie root('z');
struct trie* temp;
while(elements--){
cin >> elem;
temp = &root;
for(auto c : elem){
temp = temp->find(c);
if(temp == nullptr)
temp = temp->add(c);
}
}
cin >> elem;
cout << present(&root, elem, 0);
}
return 0;
}

你能帮我调试这个错误吗?

使用不同的结构 trie 指针来分配 trie find 方法返回值。如下所示(仅给出下面修改后的逻辑(-

while (elements--) {
cin >> elem;
temp = &root;
struct trie* exists;
for (auto c : elem) {
exists = temp->find(c);
if (exists == nullptr)
temp = temp->add(c);
else
temp = exists;
}
}