分段错误,初始化C中的递归结构

时间:2012-10-24 03:00:25

标签: c struct segmentation-fault

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

#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的新手,所以我完全不知道发生了什么。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

你似乎认为当你做

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

然后将该结构的内容初始化为零(例如,每个成员将以NULL开始)。 malloc()不是这种情况。您必须使用calloc,或使用memset()在分配后重置它。

事实上,我甚至会在你的起始词典中调用memset以保证安全。 (即使是全局变量和静态变量are apparently initialized to zero,所以这可能不适用于您的情况。)