将文件读入链接列表时出现分段错误

时间:2014-02-10 01:04:42

标签: c list file pointers segmentation-fault

我正在使用一个函数返回指向文件中下一个单词的指针,以创建文件中唯一字符串的链接列表。我没有得到我需要增加每个副本的计数的部分,因为我在尝试打印列表中的字符串时遇到“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] = '\0';
    return strdup(wordBuffer);
} 

int main() {

    char filename[50];
    printf("Enter the file name: \n");
    scanf("%s\n", 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("%s\n", curr->string);
    }

    return 0;

}

1 个答案:

答案 0 :(得分:2)

仔细查看以下代码段:

struct list *head, *tail, *curr; 
head = NULL: 
char *newWord;
while((newWord = getNextWord(file)) != NULL) {

    strcpy(curr->string, newWord);

您正在访问curr指向的对象的成员,但那是什么对象?它从未被初始化,很可能是第一次通过它进行分段。要解决此问题,请每次将其设置为新节点:

struct list *head, *tail, *curr; 
head = NULL;
char *newWord;
while((newWord = getNextWord(file)) != NULL) {
    curr = malloc(sizeof(struct list));
    strcpy(curr->string, newWord);