Home > Net >  text-file to linked-list C
text-file to linked-list C

Time:05-21

So im trying to save a text file in a linked-list (each node containing a word) and that's my code so far. It just wont even run no matter what i do. please help if you can.

#include <string.h>
#include <ctype.h>
#define W 30000
#define M 35
typedef struct node {
    char * str;
    struct node * node ;
} Node;
typedef Node * ListofChar;
typedef Node * CharNode_ptr;
Node * createnode(char text[M]);
void letters(ListofChar * lst_ptr);

int main(void){
    ListofChar chars = NULL;
    letters(&chars);
    return 0;
    }

Node * createnode(char text[M]){
    CharNode_ptr newnode_ptr ;
    newnode_ptr = malloc(sizeof (Node));
    strcpy(newnode_ptr->str, text);
    printf("%s\n", newnode_ptr->str);
    newnode_ptr -> node = NULL;
    return newnode_ptr;
    }
void letters(ListofChar * lst_ptr){
    FILE *file;
    char txt[M];
    Node *ptr;
    ptr=*lst_ptr;
    file=fopen("Notebook.txt","r");
    while ((fscanf(file,")s",txt) != EOF)){
        if (strcmp(txt,"*")){
            (*lst_ptr)=createnode(txt);
            (*lst_ptr)->node=ptr;
            ptr=*lst_ptr;}}
    fclose(file);
    return;
    }

CodePudding user response:

In createnode, you have the lines:

newnode_ptr = malloc(sizeof (Node));
strcpy(newnode_ptr->str, text);

Since newnode_ptr->str is never initialized, this is undefined behavior. Try:

newnode_ptr = xmalloc(sizeof *newnode_ptr);
newnode_ptr->str = xstrdup(text);

where xmalloc and xstrdup are the obvious wrappers around malloc and strdup that abort on failure.

  • Related