unordered_map中的EXC_BAD_ACCESS

时间:2017-08-18 17:20:57

标签: c++ unordered-map

代码是c ++ 14中的一个简单的Trie实现。弹出错误后执行add("name")函数时:EXC_BAD_ACCESS(代码= 1,地址= 0x20))

下面是一些调试图片:

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

这个问题应该是微不足道的,但我无法理解。感谢您的帮助,有任何其他优化或代码设计可以完成,请告诉我。

1 个答案:

答案 0 :(得分:2)

在3参数Trie::add功能中,当您致电createNewNode时,node已知为NULL。第三个参数node->children取消引用NULL指针,导致未定义的行为,在这种情况下,崩溃。

如果你在局部变量的值上查找调用堆栈,你可以看到它。