2017-08-18 66 views
-1

該代碼是在C + + 14簡單特里實現。當執行以下錯誤add("name")功能彈出式:EXC_BAD_ACCESS(碼= 1,地址= 0×20))EXC_BAD_ACCESS在unordered_map

遵循以下一些調試圖像:

enter image description here

enter image description here

遵循下面的代碼:

struct TrieNode { 
    string value; 
    unordered_map<char, TrieNode *> children = {}; 
}; 

class Trie { 
public: 
    TrieNode *root = new TrieNode; 

    TrieNode *find(string query); 

    int countPartialFind(string query); 

    void add(string value); 

private: 
    void add(string value, TrieNode *node); 

    TrieNode *createNewNode(string &value, int counter, unordered_map<char, TrieNode *> &children); 

    void add(string value, int counter, TrieNode *node); 

    TrieNode *findNode(char query, unordered_map<char, TrieNode *> &children); 
}; 

TrieNode *Trie::find(string value) { 
    TrieNode *tmpNode = root; 
    for (int counter = 0; counter < value.length(); counter++) { 
    tmpNode = findNode(value[counter], tmpNode->children); 
    if (tmpNode == NULL) { 
     return NULL; 
    } 
    } 

    return tmpNode; 
} 

int Trie::countPartialFind(string query) { 
    TrieNode *matchNode = find(query); 
    if (matchNode == NULL) { 
    return 0; 
    } 

    return matchNode->children.size(); 
} 

void Trie::add(string value, int counter, TrieNode *node) { 
    for (; counter < value.length(); counter++) { 
    node = findNode(value[counter], node->children); 
    if (node == NULL) { 
     node = createNewNode(value, counter, node->children);; 
    } 
    } 
} 

TrieNode *Trie::findNode(char query, unordered_map<char, TrieNode *> &children) { 
    unordered_map<char, TrieNode *>::const_iterator search = children.find(query); 
    if (search == children.end()) { 
    return NULL; 
    } 
    return search->second; 
} 

TrieNode *Trie::createNewNode(string &value, int counter, unordered_map<char, TrieNode *> &children) { 
    TrieNode *newNode = new TrieNode; 
    newNode->value = value.substr(0, counter + 1); 
    char tmp = value[counter]; 
    children[tmp] = newNode; 
    return newNode; 
} 

void Trie::add(string value) { 
    if (value.length() == 0) { return; } 
    int counter = 0; 

    TrieNode *tmpNode = findNode(value[counter], root->children); 

    if (tmpNode == NULL) { 
    tmpNode = createNewNode(value, counter, root->children); 
    } 

    add(value, ++counter, tmpNode); 
} 

這個問題應該是微不足道的,但我不能理解它。感謝您的幫助,它還有其他可以完成的優化或代碼設計,請讓我知道。

+2

您是否通過與調試程序的代碼踩找到該行實際上觸發異常? – NathanOliver

+0

是的,但沒有抓住它,對不起,錯誤可能是如此愚蠢,然後我會感到羞恥。 –

回答

2

在3參數Trie::add函數中,當您調用createNewNode時,node已知爲NULL。第三個參數node->children取消引用NULL指針,導致未定義的行爲,並且在這種情況下導致崩潰。

如果你擡頭看局部變量,你可以看到這個值調用堆棧。

+0

謝謝,問題真的很蠢,再次感謝。 –