<分区>
我正在编写一个读取字典文件(文本文件,每行一个单词)的程序,并将其插入到一个由数组“链表”组成的结构中,其中单词递归转发到 [第一个字母- 'a'] 数组的条目(这是另一个数组,处理下一个字母)。当整个单词被“消耗”时,它将单词(未更改)插入到规则的单词链表中。该程序成功处理了前 15 个单词,但在第 16 个单词时抛出段错误。
看起来段错误发生在以下代码段中的 add() 方法中:
struct LinkedList * new = (struct LinkedList *) calloc(1,
sizeof(struct LinkedList));
if (!new) {
perror("Not enough memory!"); // Error here
exit(2);
}
(希望如此)相关代码:
void addList (struct LinkedList * list, char * word) {
if (!list->next)
{
struct LinkedList * new = malloc(sizeof(struct LinkedList));
if (!new) {
perror("Not enough memory!");
exit(2);
}
char * new_word = malloc(strlen(word) * sizeof(char));
if (!new_word) {
fprintf(stderr, "Not enough memory!");
exit(2);
}
new->next = 0;
strcpy(new_word, word);
new->word = new_word;
list->next = new;
}
else
{
addList(list->next, word);
}
}
void add(struct HashTree * root, char * word, char * word_sorted, int length) {
if (length == 0) // Found the correct place
{
if (!root->words) // If words are not allocated
{
// Create list node
struct LinkedList * new = calloc(1, sizeof(struct LinkedList));
if (!new) {
perror("Not enough memory!");
exit(2);
}
char * new_word = malloc(strlen(word) * sizeof(char));
if (!new_word) {
fprintf(stderr, "Not enough memory!");
exit(2);
}
new->next = 0;
strcpy(new_word, word);
new->word = new_word;
root->words = new;
}
else // Add to the Linked List
{
addList(root->words, word);
}
}
else
{
// printf("Length_add = %d\n", length);
if (!root->next) // If the array was not allocated yet
{
struct HashTree * new = malloc(27 * sizeof(struct HashTree *));
if (!new) {
perror("Not enough memory!");
exit(2);
}
root->next = new;
}
add(&(root->next[ word_sorted[0] - 'a' ]),
word, (char *) (word_sorted +1), (length-1)); // Use the next letter.
}
}
为了节省空间,Here is the link to the full code.
这是 gdb 核心和回溯的输出:
Program terminated with signal SIGSEGV, Segmentation fault.
100 perror("Not enough memory!");
我之前用Java实现过类似的算法,算法好像是对的。我是 C 的新手,不明白可能出了什么问题。如果有任何帮助,我将不胜感激!
编辑: 删除了 sort、clean 和 cleanWords 方法(它们对向结构中添加单词影响不大)。处理第二个词时发生分割,第 125 行:
perror("Dictionary file not found!");