I am trying to implement a linked list in C. I believe I am creating and inserting elements correctly, but there is a segmentation fault every time I try to loop through. Here is my code for the linked list:
struct node {
char **data;
struct node *next;
};
Two global variables to store pointers to head and tail:
struct node *head;
struct node *tail;
Code to insert an element:
void insert(char **args)
{
struct node* pointer = (struct node*)malloc(sizeof(struct node));
pointer -> data = args;
pointer -> next = NULL;
if( head == NULL ) {
head = pointer;
tail = pointer;
}
else {
tail -> next = pointer;
tail = pointer;
}
}
I then try to go through the list and print the data contents (this successfully prints the elements in the list, but then there is a segmentation fault):
int print_list(char **args)
{
struct node *curPointer = head;
if(curPointer == NULL) {
printf("%s", "List is empty\n");
}
else {
printf("%s", "List: ");
do {
int i;
while(curPointer->data[i] != NULL) {
printf("%s", tail->data[i]);
i++;
}
printf("%s", "\n");
curPointer = curPointer->next;
}while(curPointer->next != NULL);
}
return 1;
}
Other functions in my program that rely on looping through the list have a similar segmentation fault issue.