I am getting a segmentation fault error when I run this code. I don’t get the error when I run it in gdb. I also don’t get this error when i < 17.
void test()
{
struct node *listHead=NULL;
int i=0;
while(i<17)
addTail(&listHead,createNode(i++));
}
struct node* createNode(int i)
{
struct node *n = malloc(sizeof(*n));
n->item = i;
return n;
}
void addTail(struct node **listHead, struct node *n)
{
if(*listHead!= NULL)
{
struct node *temp = *listHead;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
} else
{
*listHead= n;
}
}
You’re not initializing the new elements correctly.
Add
n->next = NULL;to thecreateNodefunction.