c - Reading in words into a linked list -
im trying write program reads each word inputted user , sticks word linked list. have tried far got seg faults not sure went wrong mallocing/pointers. (havent implemented printlist yet).
#include <stdio.h> #include <stdlib.h> #include <string.h> #define max_len 20 typedef struct node{ char *word; struct node *next; }node_t; node_t *read(node_t *node); void printlist(node_t *node); node_t *insertnode(char *word, node_t *node, int size); int main(int argc, char *argv[]) { node_t *start = null; printf("enter sentence:\n"); read(start); return 0; } void *read(node_t *node){ int i, size = max_len; char c, *word; if(!(word=malloc(size))){ printf("out of memory!\n"); exit(exit_failure); } while((c=getchar())!='\n'){ for(i=0;c!=' ';i++){ word[i]=c; if(i>size){ size=size*2; if(!realloc(word, size)){ printf("out of memory\n"); exit(exit_failure); } } } node = insertnode(word,node,size); } return node; } node_t *insertnode(char *word, node_t *node, int size){ node_t *new_node, *current; new_node = (node_t*)malloc(sizeof(node_t)); new_node->next = null; if(!(new_node->word = malloc(size))){ printf("out of memory\n"); exit(exit_failure); } strcpy(new_node->word,word); if (node == null){ node = new_node; current = new_node; } else{ current->next = new_node; current = new_node; } return node; }
there several issues:
- your prototype , implementation of
readdon't match; make both returnnode_t *. - you have 2 nested loops input, 1 reading
stdinand 1 cycling through characters. inner loop never updated condition, becauseccan changed outer loop. there should 1 loop, takes care of reading stream , writing string. - you don't keep tzhe result of
realloc, means don't reflect updates when handle allocated memory changes. in these cases, access old handle, has become invalid. - you don't terminate string null character.
- you should reallocate before access memory out of bounds. means check whether enlarge array before writing it. note array of length
n,nillegal index. - the result of
getcharshouldint, otcharvalid input distincteof, don't check.
therer more issues, ones listed ones concerned read. haven't looked linked list insertion.
in order terminate string zero, recommend write infinite loop , postpone break condition after possible reallocation. foe example:
node_t *read(node_t *node) { int size = max_len; int = 0; char *word = malloc(size); if(word == null) { printf("out of memory!\n"); exit(exit_failure); } while (1) { int c = getchar(); if(i >= size) { size = size*2; word = realloc(word, size); if (word == null) { printf("out of memory\n"); exit(exit_failure); } } if (c == '\n' || c == eof) { word[i] = '\0'; break; } word[i++] = c; } node = insertnode(word, node, size); return node; }
Comments
Post a Comment