C 代码中的奇怪分段错误

C 代码中的奇怪分段错误,c,linked-list,segmentation-fault,C,Linked List,Segmentation Fault,我真的很绝望,我不知道为什么这段代码会出现分段错误。这将在链接的末尾放置一个元素**n它从不为空,但*n可能为空 int insertaFinal(Nodo **n, int dato){ if (!*n){ insertaInicio(n,dato); return 1; } Nodo* temp = *n; while (temp->sig) temp = temp->sig; tem

我真的很绝望,我不知道为什么这段代码会出现分段错误。这将在链接的末尾放置一个元素**n它从不为空,但*n可能为空

int insertaFinal(Nodo **n, int dato){

    if (!*n){
        insertaInicio(n,dato);
        return 1;
    }

    Nodo* temp = *n;

    while (temp->sig)
        temp = temp->sig;

    temp -> sig = (Nodo*) malloc(sizeof(Nodo));
    temp = temp->sig;
    temp->dato = dato;

    return 1;
}
这没什么“奇怪”的。在这里:

while (temp->sig)
    temp = temp->sig;
您似乎希望循环,直到
temp->sig
NULL
,但当您创建新节点时,您从未将此成员首先设置为
NULL
,因此很明显,您的循环将进入未分配的内存。您需要做的是:

temp->sig = malloc(sizeof *temp->sig);
if ( !temp->sig ) {
    perror("Couldn't allocate memory for node");
    exit(EXIT_FAILURE);
}
temp = temp->sig;
temp->dato = dato;
temp->sig = NULL;    //  <---- Add this line
temp->sig=malloc(sizeof*temp->sig);
如果(!temp->sig){
perror(“无法为节点分配内存”);
退出(退出失败);
}
温度=温度->信号;
温度->数据=数据;

temp->sig=NULL;//你能解释一下(!*n){?你的意思是!=null吗?segfault发生在哪一行上?gdb怎么说?是的!应该以与c中null为false相同的方式工作这一行没有被告知。IDK为什么如果我删除temp=temp->sig;它不会得到错误如果你没有检查
malloc()
的返回,你的代码就不应该工作。