gpt4 book ai didi

有人可以帮我在这里找到段错误吗?

转载 作者:行者123 更新时间:2023-12-04 09:22:50 25 4
gpt4 key购买 nike

编辑:所以,事实证明“索引”没有返回到 0。那么。这修复了一个段错误。但仍然遇到不同的段错误。正在努力。

node* new_node(void){
node* ptr = malloc(sizeof(node));
for (int i = 0; i<27; i++) {
ptr->next[i] = NULL;
}
return ptr;
}
bool load(const char* dictionary)
{
FILE* dict = fopen(dictionary, "r");
node* ptr = new_node;
char word[LENGTH+1];
int index = 0;
for (int c = fgetc(dict); c!=EOF; c = fgetc(dict)){
if(c!='\n'){
word[index]=c;
index++;
}
else {
for(int x=0; x<=index; x++){
int ch = (word[x] == '\'') ? 26 : tolower(word[x])-'a';
if (ptr->next[ch] == NULL){
ptr->next[ch] = new_node;
}
ptr = ptr->next[ch];
}
ptr->end=true;
}
}
return true;
}

我正在尝试为字典实现一个 trie 数据结构,但我的程序似乎在这个函数的某处出现了段错误。即使在 GDB 的帮助下,我似乎也无法确定它,所以有人可以帮助我吗?

节点定义如下:

typedef struct node{
bool end;
struct node* next[27];
} node;

字典文件:

a
aaa
aaas
aachen
aalborg
aalesund
aardvark
aardvark's
aardvarks
aardwolf

(...)

最佳答案

您的代码中有很多问题:

  • 当您使用malloc 分配内存时,它是未初始化的。分配后直接初始化它,这样 NULL 指针真的是空的。 (calloc,“malloc”的表亲,将所有内存初始化为零。)

  • 当你遍历单词时,你不应该包含index:

    for (int x = 0; x < index; x++) ...
  • 当您找到一个单词的结尾时,您必须将 index 重置为 0。否则,您将追加到旧单词并溢出缓冲区。 (您可能还应该强制执行“索引”的上限。)

  • 同样,当您将单词插入到 trie 中时,您必须将 trie 遍历的指针重置为 trie 的根。这里需要两个指针:一个根节点指针和一个用于遍历 trie 的辅助指针。

  • 照原样,您的 trie 对您的函数而言是本地的。返回根节点,以便其他函数可以使用该 trie,或者在失败时返回 NULL

修复这些问题,您将拥有一个不会崩溃的功能。 (它仍然会泄漏内存并且可能无法正确构建 trie。)

    node *load(const char *dictionary)
{
FILE *dict = fopen(dictionary, "r");
node *head = calloc(1, sizeof(node));

char word[LENGTH + 1];
int index = 0;

for (int c = fgetc(dict); c != EOF; c = fgetc(dict)) {
if (c != '\n') {
word[index] = c;
index++;
} else {
node *ptr = head;

for (int x = 0; x < index; x++) {
int ch = (word[x] == '\'') ? 26 : tolower(word[x]) - 'a';
if (ptr->next[ch] == NULL) {
ptr->next[ch] = calloc(1, sizeof(node));
}
ptr = ptr->next[ch];
}
ptr->end = true;
index = 0;
}
}

return head;
}

关于有人可以帮我在这里找到段错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36310496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com