简体   繁体   中英

Floating point exception in C++ Trie

The following code for Trie implementation is throwing Floating point exception upon call to function insert. The line inside for loop to check for existing node is where the problem is.

struct Node {
    char c;
    bool isend;
    unordered_map<int, struct Node*> map;
};

void insert(struct Node* root, string contact) {
    int size = contact.size();
    char ch;

    for (int i = 0; i < size; i++) {
        ch = contact[i];
        // this check is creating problem
        if (root->map.find(ch) == root->map.end()) {
            struct Node* tmp = (struct Node*) malloc(sizeof(struct Node));
            tmp->c = ch;

            if (i == (size - 1)) {
                tmp->isend = true;
            } else {
                tmp->isend = false;
            }

            root->map.insert(make_pair(ch, tmp));
            root = tmp;            
       } else {
          root = root->map[ch];   
        }         

    }
}

int main()
{
    struct Node* root = NULL;

    root = (struct Node*) malloc(sizeof(struct Node));

    insert(root, "text");
}

Any help?

Do not use malloc in C++ code (unless you really know what you are doing)

root = new Node;

and

tmp = new Node;

The problem is that because you use malloc the constructor for Node::map is not getting called. Using new will make sure that all necessary constructors are called.

When you use malloc you are not invoking your Node class constructor, you are just allocating memory.

Use new instead which will both allocate the memory and call a constructor. So:

struct Node* tmp = (struct Node*) malloc(sizeof(struct Node));

should be:

Node* tmp = new Node();

and:

struct Node* root = NULL;
root = (struct Node*) malloc(sizeof(struct Node));

should be:

Node* root = new Node();

Remember to delete where appropriate. Or even better, use smart pointers . And above all avoid using C with classes . Use proper standard C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM