我正在为一个课程作业编写拼写检查程序。第一步是在“dict”中加载一个以“\ n”分隔的列表(实际上是一个char ** dict_main)。
加载dict的过程是下一步:
void dict_load(char *fname){
FILE *loaded_file = fopen(fname, "r");
char **aux = NULL;
int a = 0;
char word[MAX_WORD_SIZE];
//Checks whether fname was successfully loaded or not
if(loaded_file == NULL){
perror("Could not load dict\n");
exit(1);
} else {
while(fgets(word, MAX_WORD_SIZE, loaded_file) != NULL){
main_size++;
while(aux == NULL){
//To ensure that aux is not NULL
aux = realloc(dict_main, main_size);
}
dict_main = aux;
aux = NULL;
//Allocs space enough to store word
dict_main[main_size-1] = calloc(MAX_WORD_SIZE, sizeof(char));
strcpy(dict_main[main_size-1], word);
}
}
//Just for debbuging, prints each string in dict_main
for(a = 0; a<main_size; a++){
fprintf(stdout, "%s", dict_main[a]);
}
fclose(loaded_file);
}
当我正常运行它时,这似乎有效,但是当我使用valgrind时,我在尝试printf字符串时会遇到段错误。
这是程序中运行的唯一程序,这是主要的:
int main(int argc, char **argv){
char *dict;
//int i;
if (argc < 2)
{
printf("spellchecker.c: nro de argumentos erroneo. Deben ser <documento> [<diccionario>].\n");
return (1);
}
dict = (argc >=3) ? argv[2] : "dict.txt";
dict_main = calloc(main_size, sizeof(char*));
dict_load(dict);
free(dict_main);
printf("El documento %s ha sido procesado. Resultados en out.txt\n", argv[1]);
当我用valgrind运行它时,是否有一些我缺少的东西让我得到SegFault? }