I'm attempting to create a linked list in C to practice the concepts of pointers and data structures. I keep running into a segmentation fault and I've narrowed down the issue to my insertNode()
function.
#include <stdio.h>
#include <stdlib.h>
struct node {
char *value;
struct node *next;
};
typedef struct node node_t;
node_t* getNode(char *val) {
node_t *node = malloc(sizeof(node_t));
if (node == NULL) return node_t;
node->value = val;
node->next = NULL;
return node;
}
void printList(node_t *node) {
printf("%s\n", node->value);
if (node->next == NULL) return;
printList(node->next);
}
void insertNode(node_t *head, char* val) {
node_t *current = head;
while (current!= NULL) {
current = current->next;
}
node_t *newNode = getNode(val);
current->next = newNode;
}
int main() {
node_t *head = getNode("Alpha");
insertNode(head, "Bravo");
printList(head);
return 0;
}
The issue is specifically with condition in the while loop. As far as I understand, current
should initially equal head
which points to the first node in the linked list, so it should enter the loop and set current
to current->next
which is a NULL pointer. On the next iteration it will therefore not enter the loop, and then point the NULL pointer to the newly created node instead.
void insertNode(node_t *head, char* val) {
node_t *current = head;
while (current != NULL) {
current = current->next;
}
node_t *newNode = getNode(val);
current->next = newNode;
}
Changing my while loop logic to the below seems to resolve the segmentation fault and the program works as expected but I don't understand why the previous condition was causing an issue.
while (current->next != NULL) {
current = current->next;
}
Does this not just skip a step and jump to the first next pointer, I'm failing to understand why the previous while loop causes a segmentation fault and doesn't achieve the same behaviour.