2017-02-25 82 views
2

嗨,大家好我想实现一些课程的拼写检查,但我是新来的C和只加载字典文件是毁了我的头。下面的代码编译得很好,但运行时崩溃。有时打印500行后有时会打印1500行,但我不知道是什么原因造成的!字典文件崩溃,但编译好

#include <string.h> 
#include <stdio.h> 
#include <malloc.h> 

int main(int argc, char *argv[]) 

{ 
FILE *words_ptr; //pointer for words.txt 

char new_word[100]; 
char temp_word[100]; 
char *dict[45440]; 
words_ptr = fopen("dictionary.txt", "r"); 
if(words_ptr != NULL) 
{ 
    printf("File dictionary.txt opened\n"); 
    int i = 0; 
    while (fgets(temp_word, 45440, words_ptr)) 
    { 
     new_word[i] = (char)calloc(strlen(temp_word), sizeof(char)); //ensuring new_word will be the right size 
     strcpy(new_word, temp_word);  //copy contents of temp_word to new_word 
     dict[i] = new_word;    //copy contents of new_word to i'th element of dict array 
     printf("printing out dict[%d]: %s\n", i, dict[i]); 
     i++; 
    } 
    printf("printing out dictionary1: %s\n", dict[1]); 

    fclose(words_ptr); 
    return 0; 
} 
else {printf("Unable to open file words.txt\n"); return 1;} 

} 
+1

* new_word [i] =(char)calloc(strlen(temp_word),sizeof(char)); //确保new_word的大小合适*不正确。 'new_word'是一个字节太小 - 你忘记了终止'\ 0'字符的空间。 –

+1

注意:不要在C中抛出'calloc'&friends或'void *'的结果' – Olaf

+0

'fgets(temp_word,45440,words_ptr)'→'fgets(temp_word,100,words_ptr)' –

回答

2

这条线:

new_word[i] = (char)calloc(strlen(temp_word), sizeof(char)); //ensuring new_word will be the right size 

不能提供足够的空间来复制字符串。这是一个字节太短,因为strlen()不包括终止'\0'字符。

另外,new_word只有100 char条目的空间 - 它甚至不是char *。这完全是无关紧要的。只需直接保存的calloc()的结果dict[i]

dict[i] = strdup(temp_word); 

是的,有一个名为strdup()重复的字符串函数。 It's been part of the POSIX standard for about 16 years.

+0

您可能需要再次阅读代码。 – Jarvis

+0

你是冠军的感谢。我把dict [i] = strdup(temp_word);直接在那里,它工作正常! –

3

根据手册页,的释放calloc()函数的size(第二个参数)的nmemb(第一自变量)元素的数组分配内存字节每返回指向分配的存储器。内存设置为零。

你基本上是铸造一个指向char的指针,并进一步分配给char,这是没有意义的。而不是声明new_word作为一个字符数组的,使它char *,做calloc这样的:

char *new_word; 
... 
new_word = calloc(strlen(temp_word) + 1, sizeof(char)); 
+0

。那个很难发现。 –