c - linked list is crashing my program -
hello coding program accepts user input string , tokenize , store linked list. i've tested linked list manual mean word word input without using strtok() , works fine maybe there strtok(). not sure though may check implementation of linked list.
here code:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct wordnode node; struct wordnode { char *word; char *nextword; node *next; }; node *head = null; node *tail = null; node* createlist(char*, char*); node* addtolist(char*, char*); void printlist(void); int main(void) { char input[2048]; char *userword, *firstword, *nextword; gets(input); userword = strtok(input, " .,!?;:"); while(userword != null) { firstword = userword; userword = strtok(null, " .,!?;:"); nextword = userword; addtolist(firstword, nextword); } printlist(); return 0; } node* createlist(char* word, char* nextword) { node *ptr = malloc(sizeof(node)); if(ptr == null) { /*node creation failde*/ return null; } ptr->word = malloc((strlen(word) + 1)*sizeof(char)); ptr->nextword = malloc((strlen(nextword) + 1)*sizeof(char)); ptr->word = strdup(word); ptr->word = strdup(nextword); ptr->next = null; head = tail = ptr; return ptr; } node* addtolist(char* word, char* nextword) { if(head == null) { return createlist(word, nextword); } node *ptr = malloc(sizeof(node)); if(ptr == null) { /*node creation failed*/ return null; } ptr->word = malloc((strlen(word) + 1)*sizeof(char)); ptr->nextword = malloc((strlen(nextword) + 1)*sizeof(char)); ptr->word = strdup(word); ptr->word = strdup(nextword); ptr->next = null; tail->next = ptr; tail = ptr; return ptr; } void printlist(void) { node *ptr = head; while(ptr != null) { printf("\n--%s----%s--\n", ptr->word, ptr->nextword); ptr = ptr->next; } }
i removed string malloc part , noticed i've put nothing on *nextword pointer why printing random special chars.
node* createlist(char* word, char* nextword) { node *ptr = malloc(sizeof(node)); if(ptr == null) { /*node creation failde*/ return null; } //ptr->word = malloc((strlen(word) + 1)*sizeof(char)); //ptr->nextword = malloc((strlen(nextword) + 1)*sizeof(char)); ptr->word = strdup(word); ptr->nextword = strdup(nextword); ptr->next = null; head = tail = ptr; return ptr; } node* addtolist(char* word, char* nextword) { if(head == null) { return createlist(word, nextword); } node *ptr = malloc(sizeof(node)); if(ptr == null) { /*node creation failed*/ return null; } //ptr->word = malloc((strlen(word) + 1)*sizeof(char)); //ptr->nextword = malloc((strlen(nextword) + 1)*sizeof(char)); ptr->word = strdup(word); ptr->nextword = strdup(nextword); ptr->next = null; tail->next = ptr; tail = ptr; return ptr; }
Comments
Post a Comment