I have problems when adding nodes to a singly linked list, for some reason the
if(current->next == NULL)
gets skipped when the list is empty, and this causes a seg fault when I display the list... I'm really confused as to why it's getting skipped any ideas?
void addToList(node** head, char name[30], int groupSize, boolean inRest){
//create new node
node *newNode = (node*)malloc(sizeof(node));
if (newNode == NULL) {
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}
InitNodeInfo(newNode, name, groupSize, inRest);
node *current = head;
//check for first insertion
if (current->next == NULL) {
current->next = newNode;
printf("added at beginning\n");
} else {
//else loop through the list and find the last
//node, insert next to it
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("added later\n");
*head = current;
}
if (debug == FALSE) { //debug mode...
printf("Pushed the value %d on to the stack\n", groupSize);
} else {
printf("\n\nATTENTION : Group cannot be added, the name entered already exists!\n\n");
}
}
headandcurrent. Maybe you wantnode *current = *head;. Then what happens when you add it at the beginning? At present you print only, but do not reassign/movehead. Actually, you do it in the other case...headpoint to NULL or there is always a dummy element at the beginning? (i.e. head points to a dummy element)