链接列表C错误

Hna*_*Hna -2 c

我运行此代码时出现分段错误错误.我在gdb中运行它时没有收到错误.当我<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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 6

您没有正确初始化新元素.

添加n->next = NULL;createNode功能.