I have written my own linked list implementation in C, and it works fine for storing values, but whenever I try to run through the list I get a segmentation fault. I'm not sure why the issue arises, and I spent a decent amount of time trying to run through the program myself but to no avail. Could you guys help me find the reason for the error? Here is my code:
#include <stdlib.h>
#include <stdio.h>
// A double linkd list node
struct list
{
struct list * prev;
int data;
struct list * next;
};
typedef struct list node;
node *head = NULL;
node *tail = NULL;
// Adds an item to the end of the list
void append(int item);
// Adds an item at the given index
int insert(int item, int index);
// Removes and returns an item at the specified index
int remove_node(int index);
// Gets an item at the specified index
int get(int index);
// Returns the node at the specified index
node* get_node(int idex);
// Adds an item to the end of the list
void append(int item)
{
// If no items have been added to the list yet
if(head == NULL)
{
head = (node*) malloc(sizeof(node));
head->prev = NULL;
head->data = item;
head->next = NULL;
tail = head;
printf("Successfully added the head\n");
}
// If items have previously been added to the list
else
{
node *current = (node*) malloc(sizeof(node));
printf("Successfully allocated memory for the next item\n");
current->prev = tail;
printf("Assigned current previous link to tail\n");
current->data = item;
printf("Assignd current's data value: %d\n", item);
current->next = NULL;
printf("Assigned current's next value to NULL\n");
tail = current;
printf("Assigned tail to current\n\n\n");
}
}
// Adds an item at the given index
// Returns an int. Nonzero means there was an error
int insert(int item, int index)
{
node *current, *new;
current = head;
for( ; index > 0; index--)
{
current = current->next;
}
// Make a new node and properly connect it
new = (node*) malloc(sizeof(node));
new->prev = current->prev;
new->data = item;
new->next = current;
current->prev = new;
return 0;
}
// Removes and returns an item at the specified index
int remove_node(int index)
{
int ret;
node *current = head;
for( ; index > 0; index--)
{
current = current->next;
}
ret = current->data;
// Connect the nodes on both sides of current
(current->prev)->next = current->next;
(current->next)->prev = current->prev;
free(current);
return ret;
}
// Gets an item at the specified index
int get(int index)
{
return (get_node(index))->data;
}
// Returns the node at the specified index
node* get_node(int index)
{
node *current = head;
for( ; index > 0; index--)
{
current = current->next;
}
return current;
}
int main(void)
{
int i;
for(i = 0; i < 10; i++)
{
append(i);
}
node *current = head;
for(i = 0; i < 10; i++)
{
printf("%d\n", current->data);
current = current->next;
}
return 0;
}