开发者

Linked List C Error [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

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.

  1. Try using calloc(1, sizeof(node))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜