我正在编写一个函数来将文件中的所有单词提取到char * 中。最初我只是简单地返回char * 但是我改变了这一点,试图回避那些被认为是不好的做法。 这是精简代码:
int main(int argc, char * argv[]){
char ** searchWords;
FILE * fp = fopen("input.txt", "r");
getSearchWords(&searchWords, fp);
return 0;
}
void getSearchWords(char *** searchWordList, FILE * searchFile){
int wordIndex = 0, scalar = 1;
char ** searchList = malloc(sizeof(char*)*DEFAULT_SEARCH_LENGTH);
for(int i = 0; i < DEFAULT_SEARCH_LENGTH; i++)
*(searchList + i) = malloc(sizeof(char)* MAX_SEARCH_LENGTH);
while(fgets(*(searchList + wordIndex), MAX_SEARCH_LENGTH + 1, searchFile)!= NULL){
if(wordIndex == (DEFAULT_SEARCH_LENGTH*scalar - 1 )){
scalar++;
searchList = realloc(searchList, sizeof(char *) * DEFAULT_SEARCH_LENGTH*scalar);
for(int i = wordIndex+1; i < DEFAULT_SEARCH_LENGTH*scalar ; i++)
*(searchList + i) = malloc(sizeof(char) * MAX_SEARCH_LENGTH );
}// if
wordIndex++;
}// while
fclose(searchFile);
printf("%d\n", wordIndex);
for(int i = 0; i < wordIndex; i++){
*(searchWordList + i) = (searchList + i);
printf("%s\n", **(searchWordList + i));
}
}
分段错误来自最后一个for循环,但是当我运行gdb时,这就是我得到的,我不知道为什么或该怎么做:
Program received signal SIGSEGV, Segmentation fault.
0x00000000006034c8 in ?? ()
(gdb) bt
#0 0x00000000006034c8 in ?? ()
#1 0x00000000006034d0 in ?? ()
#2 0x00000000006034d8 in ?? ()
#3 0x00000000006034e0 in ?? ()
#4 0x00000000006034e8 in ?? ()
#5 0x00000000006034f0 in ?? ()
#6 0xf9d384796456d39a in ?? ()
#7 0x00000000004009e0 in __ctype_b_loc@plt ()
#8 0x00007fffffffe850 in ?? ()
#9 0x0000000000000000 in ?? ()
由于
编辑: 忘记提到输入文件“input.txt”包含15个单词,每个单词在一行上。在最后的for循环中,它打印所有这些,然后点击分段错误。此外,即使我将循环的迭代次数减少1,它仍然会有段错误。