I implemented a Linked List in C.
The problem is that whenever I try to print the nodes data using the function print_list(struct linked_list *list) I get a segmentation fault.
I am not sure what is causing it because, when I try print(struct linked_list *list), it works fine.
And, when I try allocating the memory dynamically it works fine also. But I am curious what is wrong with the code this way? And why using print won't lead to the same error?
#include <stdio.h>
#include <stdlib.h>
struct node{
char data;
struct node* next;
};
struct linked_list{
struct node *head;
};
void concat(struct linked_list* list1, struct linked_list* list2)
{
struct node* tmp = list1->head;
while(tmp->next != NULL)
tmp = tmp->next;
tmp->next = list2->head;
}
void print_list(struct linked_list *list)
{
struct node* tmp = list->head;
while(tmp != NULL){
printf("%c - ", tmp->data);
tmp = tmp->next;}
printf("\n");
}
void print(struct linked_list *list)
{
struct node* tmp = list->head;
printf("%c\n", tmp->data);
tmp = tmp->next;
printf("%c\n", tmp->data);
tmp = tmp->next;
printf("%c\n", tmp->data);
}
int main()
{
struct linked_list list1,list2;
struct node n1,n2,n3,n4,n5;
n1.data = 'A';
n2.data = 'B';
n3.data = 'C';
n4.data = 'D';
n5.data = 'E';
n1.next = &n2;
n2.next = &n3;
n4.next = &n5;
list1.head = &n1;
list2.head = &n4;
printf("List 1 containes :\n");
print_list(&list1);
concat(&list1,&list2);
printf("List 1 after concat: \n" );
print_list(&list1);
return 0;
}
NULLasnextlink. You create your nodes as local data without initializing them, which in C means they have "garbage" values. Sayingstruct node n1 = {'a'};should work. Thenextfield is implicitly initialized to a null pointer.