分段故障 - 无法理解故障原因

时间:2012-09-05 11:41:47

标签: c segmentation-fault

我不明白这里的分段错误的原因。 代码是:

struct node {
    int data;
    struct node* next;
};

void add(int a,struct node *lista)
{
    struct node *p;
    p=(struct node*)malloc(sizeof(struct node*));

    p->data=a;
    p->next=NULL;

    while(lista->next!=NULL)       <--- The segmentation fault is here. 
        lista=lista->next;                    
    lista->next=p;

    return lista;

}

int main(void)
{
    struct node *list=NULL;
    list_print(list);

    list=node123();
    list_print(list);

    add(7, &list);
    list_print(list);

    return 0;
}

添加功能,它将新节点添加到列表的末尾,在朋友计算机和设置上完美地工作。我得到分段错误。我认为问题是lista->next表达式,但我不明白为什么。有什么想法吗?

5 个答案:

答案 0 :(得分:2)

void add(int a,struct node *lista) ...第二个参数是结构节点指针。

struct node *list=NULL; - list是结构节点指针。

add(7, &list); - &amp; list是结构节点**;这是不正确的,可能导致add()的`while(list-&gt; next!= NULL)无法解除引用。

答案 1 :(得分:1)

p = (struct node*)malloc(sizeof(struct node*));

这当然是错的。您不能分配大小为指针本身的内存,但必须与实际结构一样大。使用

p = malloc(sizeof(struct node));

甚至更好

p = malloc(sizeof(*p));

<强> And don't for the love of God cast the return value of malloc().

另外,您将list声明为struct node *,而您的add()函数也需要struct node * - 因此传递其地址是错误的到功能。而不是

add(7, &list);

add(7, list);

答案 2 :(得分:0)

1 - 你必须在writhin lista-&gt; next

之前检查lista是否为空

2 - malloc中有错误: p=(struct node*)malloc(sizeof(struct node));

要分配的大小是node的大小,您分配了指针struct node*的大小。

3 - add(7 , lista)而非add(7 , &lista)因为lista已经是指针。

答案 3 :(得分:0)

你正在传递列表的地址,但是函数只需要一个指针,为了通过引用传递'list',你必须将添加的判断变为:

void add(int a,struct node **lista);

然后使用(* lista)而不仅仅是'list'。例如:(* lista) - &gt; next ...

答案 4 :(得分:0)

您声明'add'不返回任何类型的数据(void)。但是你要回“'列表'了。要么使函数在指向'list'的指针上工作(将** list作为参数而不是* list)。或使其返回列表类型:struct list * add(

相关问题