c++ - EXC_BAD_ACCESS in unordered_map -


the code simple trie implementation in c++14. when executing add("name") function following error pops-up: exc_bad_access (code=1, address=0x20))

follows below debugging images:

enter image description here

enter image description here

follows code below:

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;   (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) {   (; 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); } 

the issue should trivial can't catch it. helping, there other optimizations or code design done please let me know.

in 3 parameter trie::add function, when call createnewnode, node known null. 3rd parameter, node->children, dereferences null pointer, resulting in undefined behavior and, in case, crash.

if call stack @ values of local variables can see this.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -