Search code examples
c++pointersdata-structurestrie

Getting a segmentation fault while implementing Trie in c++


Another day another seg fault I don't understand, I'm trying to implement tries for the first time and it is proving to be quite some challenge, I think it would be very helpful if someone could tell me what I'm doing wrong, would probably help me understand OOP better too I suppose, because I think the error is related to that.

The fault happens while searching and I wasn't able to understand it using the debugger myself.

Here is the code:

#include <vector>
#include <iostream>

using std::string, std::cout, std::vector;

class TrieNode {
    private: 
        bool isLeaf;
        vector<TrieNode*> ar = vector<TrieNode*>(26);

    public:
        TrieNode() {
            isLeaf = false;
            for(int i = 0; i < 26; i++) ar[i] = nullptr;
        }

    void insert(TrieNode *root, string key) {
        TrieNode *crawl = root;
        for(int i = 0; i < key.size(); i++) {
            if(!crawl->ar[key[i]]) {
                crawl->ar[key[i]] = new TrieNode();
            }
            crawl = crawl->ar[key[i]];
        }
        crawl->isLeaf = true;
    }

    bool search(TrieNode *root, string key) {
        TrieNode *crawl = root;
        for(int i = 0; i < key.size(); i++) {
            if(!crawl->ar[key[i]]) {
                return false;
            }
            crawl = crawl->ar[key[i]];
        }
        return crawl->isLeaf;
    }
};

int main() {
    TrieNode* head = new TrieNode();
    head->insert(head, "hello");
    cout << head->search(head, "hello");
}

Solution

  • Make your ar[key[i]] to something like ar[key[i]-'a'] if your string is say always lower-case.

    Basically, key[i] is a char in the range of ['a'-'z']. When it's implicitly converted to an int, it's not in the range of [0,25], but rather equal to their ascii values.