say I have the following code for inserting a node at the end to a linkedlist:
int main() {
struct Node* head = NULL;
newNode(head, 1);
newNode(head, 2);
newNode(head, 3);
print(head);
return 0;
}
void newNode(struct Node* head, int val) {
struct Node* curr_p = head;
struct Node* new_p = malloc(sizeof(struct Node));
new_p->data = val;
new_p->next = NULL;
if (head == NULL) {
curr_p = new_p;
// printf("head %d \n", head->data);
}
else{
while (curr_p->next != NULL) {
curr_p = curr_p->next;
}
curr_p->next = new_p;
}
}
void print(struct Node* head) {
struct Node* curr_p = head;
while (curr_p != NULL) {
printf("%d\n", curr_p->data);
curr_p = curr_p->next;
}
}
It appears what causes the error is in the if statement block where head == NULL
, the head node pointer seems to unable to point to new node. I always ended up with a segmentation fault. any reason for this?