Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

text-file to linked-list C

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,"%29s",txt) != EOF)){
        if (strcmp(txt,"*")){
            (*lst_ptr)=createnode(txt);
            (*lst_ptr)->node=ptr;
            ptr=*lst_ptr;}}
    fclose(file);
    return;
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading