Nathan.C.Jones
Nathan.C.Jones

Reputation: 13

Linked List not linking properly

This is just a snippet of my code. This function should create a linked list from a given file "dictionary.txt" which contains one word on each line, but I simply can't seem to get the links to work properly. When I run the code I get the first 2 entries properly (a,aa) but then it skips straight to the last entry (zyzzyvas) and a seg fault and it skips all other 80000 or so entries between.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct word {
    char entry[64];
    struct word *next;
}   WORD;

WORD *Dstart, *Dend, *curr;

WORD* makeDictionary() {

    FILE *fp;
    fp=fopen("dictionary.txt","r");

    fgets(Dstart->entry,63,fp);
    fgets(Dend->entry,63,fp);
    Dstart->next=Dend;
    int count=1;
    while(!feof(fp))
    {
        curr = (WORD *) malloc(sizeof(WORD));
        fgets(curr->entry,63,fp);
        Dend->next=curr;
        Dend=Dend->next;
        Dend->next=NULL;
        count++;
    }
    int i;
    curr=Dstart;
    for (i=1;i<=20;i++)    //Just to test if it's linking
    {
        printf("%s",curr->entry);
        curr=curr->next;
    }
}

int main {

    // curr = (WORD *) malloc(sizeof(WORD)); moved to the while loop
    Dstart = (WORD *) malloc(sizeof(WORD));
    Dend = (WORD *) malloc(sizeof(WORD));
    Dstart->next=NULL;
    Dend->next=NULL;

    makeDictionary();
    return(0);
}

Edit: Thank you Matt and interjay, moving the curr malloc into the while body fixed the problem I was having. Fixed my code.

Upvotes: 0

Views: 100

Answers (1)

interjay
interjay

Reputation: 110108

You are only ever allocating three nodes (at program initialization), and overwriting one of them repeatedly. You need to allocate a new node for each line in the file. For example, you can move the line curr = malloc(sizeof(WORD)); to the beginning of the while loop body.

Upvotes: 1

Related Questions