我是 c++ 新手,最近在学习 trie 数据结构。当我为 Trie 实现头文件时,我遇到了无法解决的分段错误。我使用典型的打印输出方法找到错误的位置,结果发现这一行
temp->isEmpty = true;
有问题,我不知道它有什么问题。这是我的头文件代码,有人可以看看并帮助我吗?
#ifndef _TRIE_HPP_
#define _TRIE_HPP_
#include <iostream>
using namespace std;
class Node{
public:
Node* children[26];
bool isEmpty;
string val;
Node(){
this->isEmpty = false;
this->val = "";
for(int i = 0; i<26; i++){
this->children[i] = nullptr;
Node* temp = this->children[I];
//temp->val = ""; //if I add this line it will also cause segmentation fault
temp->isEmpty = true; // this line causes segmentation fault
}
}
~Node();
void insert(string word);
};
#endif
void Node::insert(string word){
Node* temp = this;
const char* InputLetter = word.c_str();
int countRepeat = 0;
int index = 0;
for(int i = 0; i < word.length(); i++){
index = (int) InputLetter[i] - 'A';
if(temp->children[index]->isEmpty == false){ //causing segmentation fault
countRepeat++;
if(countRepeat == word.length()){
cout << "failure" << endl; //if word is already in the trie
return;
}
}
temp = temp->children[index];
}
cout << "success" << endl; //if insertion is successful
return;
}
int main(){
string input;
Node* myTrie = new Node(); // this line causes segmentation fault
cin >> input;
myTrie->insert(input);
}
我也试过了
temp->children[i]->isEmpty = true;
但这也会引发分段错误
数组
children
未初始化,因此将其元素之一分配给temp
然后解引用temp
意味着解引用不确定指针。
相反,您应该将数组初始化为
nullptr
.
Node(){
this->isEmpty = false;
this->val = "";
for(int i = 0; i<26; i++){
children[i] = nullptr; // initialize array elements
}
}
此外,在
insert
函数中,一行
if (temp == nullptr) break;
应该在行前插入
if(temp->children[index]->isEmpty == false){
避免取消引用
nullptr
.