分段错误,在C中初始化递归结构
好的,我把问题代码的一个简化示例放在一起:分段错误,在C中初始化递归结构,c,struct,segmentation-fault,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;
#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;
}
}
#包括“stdio.h”
#包括“string.h”
结构Trie{
//保留字母a-z的子尝试
结构Trie*sub[26];
//这是一个子串,还是一个完整的单词?
int是_字;
};
typedef结构Trie-Trie;
Trie字典;
int main(int argc,char*argv[]){
//词表
字符*字[7]={“the”,“of”,“and”,“to”,“a”,“in”,“that”};
//将单词添加到Trie结构中
int i=0,wordlen;
Trie*子目录;
for(;isub[c-97]==NULL)
sub_dict->sub[c-97]=(Trie*)malloc(sizeof(Trie*));
//设置为新的子目录
sub_dict=sub_dict->sub[c-97];
j++;
}
sub_dict->is_word=1;
}
}
基本上,我有一个包含字母“a”到“z”的Trie数据结构。我有一个单词列表,应该添加到while
循环中。不幸的是,我在循环的不同点上遇到了分段错误(取决于我运行它的时间)
我猜问题与线路有关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))代码>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))代码>你似乎认为
something = (Trie*) malloc(sizeof(Trie*));
然后将该结构的内容初始化为零(例如,每个成员将以NULL开头)。但事实并非如此。您必须使用,或在分配后使用重置它
事实上,为了安全起见,即使在你开始使用字典时,我也会叫memset。(即使是全局变量和静态变量,所以这对于您的案例来说可能不是必需的。)您似乎认为当您这样做时
something = (Trie*) malloc(sizeof(Trie*));
然后将该结构的内容初始化为零(例如,每个成员将以NULL开头)。但事实并非如此。您必须使用,或在分配后使用重置它
事实上,为了安全起见,即使在你开始使用字典时,我也会叫memset。(即使是全局变量和静态变量,所以这对于您的情况可能不是必需的。)如果我执行Trie temp;子目录->子目录[c-97]=&temp代码>而不是?这不应该和使用malloc
做同样的事情吗?因为你写的东西超出了分配的内存的末尾,所以你践踏了malloc()
的控制信息,所以它对下一步应该给你哪个内存感到困惑。如果我做Trie temp;子目录->子目录[c-97]=&temp代码>而不是?这不应该和使用malloc
做同样的事情吗?因为你写的东西超出了分配的内存的末尾,所以你践踏了malloc()
的控制信息,所以它对下一步应该给你哪个内存感到困惑。那么,这个结构会被一堆垃圾填满吗?是不是只有运气,sub_dict->sub[c-97]==NULL
才能给出预期的结果?是;使用calloc()
获取零内存。malloc()
返回的数据可能包含任何类型的垃圾;它最多只是意外地归零了。那么,这个结构会被一堆垃圾填满吗?是不是只有运气,sub_dict->sub[c-97]==NULL
才能给出预期的结果?是;使用calloc()
获取零内存。malloc()
返回的数据可能包含任何类型的垃圾;它最多只是意外地归零了。