Segmentation fault while reading a file into a linked list

Josh

I'm using a function that returns a pointer to the next word in the file to create a linked list of the unique strings in the file. I haven't gotten to the part where I need to increment the count for each duplicate because I'm getting a "Segmentation fault (core dumped)" error while trying to print the strings in the list. Right now I'm guessing that it has something to do with me not properly handling the NULL at the end of the file, but I really don't know what I would do to fix that. Any help on this issue would be very much appreciated and thank you for your time.

#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;

}

jerry

Take a close look at the following snippet:

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

    strcpy(curr->string, newWord);

You are accessing a member of the object pointed to by curr, but what object is that? It is never initialized, it's quite likely the first access through it that you're seg-faulting. To solve it, set it to a new node each time through:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related