我正在编写一个函数来将文件中的所有单词提取到 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,它仍然会出现段错误。