I am trying to add an item to the linked list by traversing the list to create the next node. and the last node in the list to point to the newly created node. But I am getting a core dump segmentation fault on it.
void linked_list_add(list_node_t *head, void *item)
{
list_node_t *temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
list_node_t *new_node = (list_node_t *)malloc(sizeof(list_node_t));
new_node->data = item;
new_node->next = NULL;
new_node->prev = temp;
//if(temp != NULL)
// temp->next = new_node;
// new_node->prev = temp;
}
TEST_F(LinkedList, Add)
{
int i = 3;
linked_list_add(list, &i);
ASSERT_EQ(list->next->data, &i);
i = 4;
linked_list_add(list, &i);
ASSERT_EQ(list->prev->data, &i);
i = 5;
linked_list_add(list, &i);
ASSERT_EQ(list->next->data, &i);
}
tempever be null?temp->next = new_node;that will preserve forward searching your linked list as well as the backward searching that you currently preserve with the existingnew_node->prev = temp;the way the code is written when a new node is inserted the old tail node'snextpointer is not set to point to the newly added nodelist:)list->prev, the element before the head of the list, should always be NULL, shouldn't it? This line will always seg fault:ASSERT_EQ(list->prev->data, &i);. Even after the fix proposed by Lucas Roberts.