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

Getting segmentation fault in my trie implementation

我为 trie 实现编写了一个 C++ 程序。但是在得到输入string(这里命名为elem

后显示segmentation fault
#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;
}

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

使用不同的 struct trie 指针来分配 trie 查找方法 return 值。类似下面的内容(仅在下面给出修改后的逻辑)-

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;
            }
        }