我正在使用一个函数,该函数返回指向文件中下一个单词的指针,以创建文件中唯一字符串的链表。我还没有到需要为每个重复增加计数的部分,因为我在尝试打印列表中的字符串时遇到了"Segmentation fault(core dumped)"错误。现在我猜测这与我没有正确处理文件末尾的NULL有关,但我真的不知道该怎么办。如果能在这个问题上提供任何帮助,我们将不胜感激,并感谢您抽出时间。
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_LEN 256
struct list {
int count;
char string[MAX_WORD_LEN];
struct list *next;
};
char* getNextWord(FILE* fd) {
char c;
char wordBuffer[MAX_WORD_LEN];
int putChar = 0;
while((c = fgetc(fd)) != EOF) {
if(isalnum(c)) break;
}
if (c == EOF) return NULL;
wordBuffer[putChar++] = tolower(c);
while((c = fgetc(fd)) != EOF) {
if(isspace(c) || putChar >= MAX_WORD_LEN -1) break;
if(isalnum(c)) {
wordBuffer[putChar++] = tolower(c);
}
}
wordBuffer[putChar] = ' ';
return strdup(wordBuffer);
}
int main() {
char filename[50];
printf("Enter the file name: n");
scanf("%sn", filename);
FILE *file = fopen(filename, "r");
struct list *head, *tail, *curr;
head = NULL:
char *newWord;
while((newWord = getNextWord(file)) != NULL) {
strcpy(curr->string, newWord);
free(newWord);
if(head == NULL)
head = curr;
else
tail->next = curr;
tail = curr;
tail->next = NULL;
}
fclose(file);
for(curr = head; curr != NULL; curr = curr->next) {
printf("%sn", curr->string);
}
return 0;
}
仔细查看以下片段:
struct list *head, *tail, *curr;
head = NULL:
char *newWord;
while((newWord = getNextWord(file)) != NULL) {
strcpy(curr->string, newWord);
您正在访问curr
指向的对象的成员,但那是什么对象?它从未初始化过,很可能是您第一次通过它进行seg错误访问。要解决此问题,请每次通过以下方式将其设置为一个新节点:
struct list *head, *tail, *curr;
head = NULL;
char *newWord;
while((newWord = getNextWord(file)) != NULL) {
curr = malloc(sizeof(struct list));
strcpy(curr->string, newWord);