繁体   English   中英

分割错误,在C中初始化递归结构

[英]Segmentation fault, initializing recursive struct in C

好的,我整理了问题代码的简化示例:

#include "stdio.h"
#include "string.h"

struct Trie{
    //Holds sub-tries for letters a-z
    struct Trie *sub[26];
    //Is this a substring, or a complete word?
    int is_word;
};
typedef struct Trie Trie;

Trie dictionary;

int main(int argc, char *argv[]){
    //A list of words
    char *words[7] = {"the","of","and","to","a","in","that"};

    //Add the words to the Trie structure
    int i=0, wordlen;
    Trie *sub_dict;
    for (;i<7; i++){
        //Reset
        printf("NEW WORD\n");
        sub_dict = &dictionary;
        //Add a word to the dictionary
        int j=0, c;
        while (c = words[i][j], c != '\0'){
            printf("char = %c\n",c);
            //Initialize the sub-Trie
            if (sub_dict->sub[c-97] == NULL)
                sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));
            //Set as new sub-trie
            sub_dict = sub_dict->sub[c-97];
            j++;
        }
        sub_dict->is_word = 1;
    }
}

基本上,我有一个Trie数据结构,其中包含字母“ a”至“ z”。 我有一个单词列表,应该在while循环中添加。 不幸的是,我在循环的不同点遇到了分段错误(取决于运行它的时间)。

我猜这个问题与生产线有关
sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*));
但是我是C新手,所以我完全不知道发生了什么。

sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie*)); 有一个错误。

在32bit操作系统中, sizeof(Trie*)将为4,因为Trie*是一个指针,而在32bit操作系统中,指针的大小为4。您可以这样操作: sub_dict->sub[c-97] = (Trie*) malloc(sizeof(Trie));

您似乎以为

something = (Trie*) malloc(sizeof(Trie*));

然后将该结构的内容初始化为零(例如,每个成员将以NULL开头)。 使用malloc()并非如此。 您必须使用calloc ,或者使用memset()在分配后将其重置。

实际上,即使在您的起始词典中,我也会称呼memset为安全起见。 (即使全局变量和静态变量显然都初始化为零 ,因此对于您的情况也可能不是必需的。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM