I have a problem in this piece of code with linked lists. It gives me the error:
Segmentation Fault (Core Dumped)
Can anyone see what seems to be the problem? Thanks in advance.
pos stands for position and root for the first element
typedef struct
{
element *root;
int size;
} list;
typedef struct _element
{
char *str;
struct _element *next;
} element;
int
insert_list (list * lst, const char *value, int pos)
{
element *new;
int k;
new = malloc (sizeof (element));
for (k = 0; k < pos; k++)
{
new = lst->root;
lst->root = lst->root->next;
if (k == pos - 1)
{
lst->root = NULL;
new->str = value;
}
}
for (k = 0; k <= lst->size; k++)
{
new = lst->root;
lst->root = lst->root->next;
if (k == lst->size)
{
lst->root = NULL;
new->str = value;
}
if (pos < 0 || pos >= lst->size)
return -1;
else
return pos;
}
}
first? You dereference it before any assignment!