I'm trying to understand linked list by writing a program but I seem to meet with wierd problems. Can anyone be helpful enough to help?
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
typedef struct stringnode{
char *string; //pointer to string
struct stringnode *next; //points to next node
} node;
void printlist(node *);
void printtable();
void addnode(node **);
void main(){
int input=1;
printf("\n\nWelcome to the Linked List Creation Program v1.0!!");
printf("\nThis program tests out the implementation of one linked list\n");
node *linklist=NULL; //creates a pointer of type node which points to NULL
while (input!=0){
printlist(linklist);
printtable();
scanf("%d", &input);
switch(input){
case 1:
addnode(&linklist);
break;
case 2:
break;
case 0:
printf("Program Terminating...");
break;
default:
printf("Command not recognized!");
break;
} // End of switch function
} // End of while
return;
}
....
void addnode(node **list){
int addPlace, x;
char word[101];
node *temp, *temp2;
temp = (node *)malloc(sizeof(node)); //flag one
temp = *list;
printlist(*list);
printf("\n\nPlease input the word you wish to add (enter any number to exit)");
//fgets(word, sizeof(word), stdin);
scanf("%s", &word);
if (isdigit(word[0])) return; //terminates function if data is numeric
printf("Where do you wish to add the new node after (0 to add at top)?");
scanf("%d", &addPlace);
printf("string:%s", word);
printf("\nnumber: %d", addPlace);
if(addPlace > 1 ){
for(x=1;x<addPlace;x++){
temp = temp->next;
}
} // end of if
if(*list == NULL){ //for first node only
temp2 = (node *)malloc(sizeof(node));
temp2->next = NULL;
strcpy(temp2->string, word);
*list = temp2;
} else {
temp2 = (node* )malloc(sizeof(node)); //flag two
temp2->next = temp->next; //flag three
strcpy(temp2->string, word);
temp->next = temp2;
}
//free(temp2);
printf("\nWord is added successfully...");
return;
}
To save space I ... the two functions which I believe have nothing to do with the problem. Within the main there is a loop which accesses the function addnode whenever I choose. My problem now is that when I access addnode for the second time after looping while once, my program terminates prematurely at the temp = (node *)malloc(sizeof(node)) which I commented //flag one on the code. If I comment that line, the program would terminate prematurely at the temp2 = (node*)malloc(sizeof(node)) which I commented //flag two. If I continue to comment that line, my program terminates prematurely at the place which I commented //flag three.
Its really frustruating because I do not get any syntax errors with the compiler and I cannot debug. Can Anyone help me with it?