Problems creating linked list in while loop. Getting runtime error on second run in loop -
i writing program puts each line of text in node in linked list. want create new node each line in text. program crashes during second run in while loop. after testing think has strncpy-function, not sure. going wrong here?
#include <stdio.h> #include <stdlib.h> #define maxbuf 50 struct node { char data[maxbuf]; struct node *next; }; int main(void) { file *f; f = fopen("text.txt", "r"); if (f == null) exit("error\n"); struct node *root = null; struct node *pointer = null; root = malloc(sizeof(struct node)); pointer = root; char buf[maxbuf]; while(fgets(buf, maxbuf, f) != null) { strncpy(pointer->data, buf, maxbuf); pointer->next = malloc(sizeof(struct node)); pointer->next = null; pointer = pointer->next; } fclose(f); }
pointer->next = null; pointer = pointer->next; thus next time round loop:
while(fgets(buf, maxbuf, f) != null) { strncpy(pointer->data, buf, maxbuf); pointer->data deference null. want test pointer null before strncpy , create malloc'd node there.
note never seem free of these nodes either.
Comments
Post a Comment