Linked List C Error [closed]
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 = *lis开发者_高级运维tHead;
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 the createNode
function.
Well, there's the fact that you have insertTail
in the main but addTail
in the code.
You're using 'malloc' which does NOT clear(fill with zeros) the memory space it allocates before it hands it back toyour. In your first case(adding the head), addTail simply makes the newly allocated node the list head, complete with a very probably non-null 'next' field.
- Try using calloc(1, sizeof(node))
精彩评论