typedef struct tag_linked_list linked_list;
struct tag_linked_list
{
int value;
linked_list* next;
};
typedef struct tag_list list;
struct tag_list
{
int size;
linked_list* data;
};
void list_insert(list* lst, int x)
{
printf("lst->data %p\n",lst->data);
lst->size++;
// create a new node
linked_list node;
node.value = x;
node.next = lst->data;
// make it the new head
printf("node %p\n",&node);
lst->data = &node;
printf("lst->data %p\n",lst->data);
}
int list_delete(list* lst)
{
// get the element at the head
printf("lst->data %p\n",lst->data);
int value = lst->data->value;
printf("value %d\n",value);
linked_list tmp;
tmp = *(lst->data->next);
printf("tmp %d\n",tmp.value);
// delete the old node
// todo: check for memory leak
//lst->data->next = NULL;
lst->size--;
// make the next element of head as the new head
lst->data = &tmp;
// return the deleted element
return value;
}
#include <stdio.h>
#include "queue.c"
int main()
{
list new_list;
printf("before seg fault\n");
list_insert(&new_list,3);
printf("after insert: %d\n", new_list.data->value);
list_insert(&new_list,4);
printf("after insert\n");
list_insert(&new_list,5);
printf("after insert\n");
for (int i = 0;i < new_list.size;i++)
{
int n = list_delete(&new_list);
printf("list[%d]: %d\n", i, n);
}
return 0;
}
The output printed as:
before seg fault
lst->data 0x400550
node 0x7fff75dbd3c0
lst->data 0x7fff75dbd3c0
after insert: 3
lst->data 0x7fff75dbd3c0
node 0x7fff75dbd3c0
lst->data 0x7fff75dbd3c0
after insert
lst->data 0x7fff75dbd3c0
node 0x7fff75dbd3c0
lst->data 0x7fff75dbd3c0
after insert
lst->data 0x7fff75dbd3c0
value 1977340928
Segmentation fault
I don't understand why every time, the list_insert method is entered and new linked_list node is created the address of the node is shown to be the same.
I need some help please.
Thanks.