2017-07-15 117 views
-1

在我應用Google獲得的一些排序方法(http://teknosrc.com/linked-list-in-c-insertion-sort/)之後,我的函數插入不起作用。C - 分段錯誤 - 鏈接列表的插入錯誤函數

首先,我要去它使用結構:

// This is the Node , where will be stored the item 

struct no 
{ 
     Item * item; 
     struct no *prox; 
}; 
typedef struct no No; 

//This is the list, where will have the head node(No) 

struct lista 
{ 
     char *nomeLista; //This is just a name of the list 
     No *cabeca; //This is the head node 
     int tamanho; //This is the amount of items inserted (forgot to implement this) 
     struct lista *prox; //This is the next list 
}; 
typedef struct lista Lista; 

//This is just the main list that will guard all the list of nodes in a linked way. No need to worry about this. 

struct vetorListas 
{ 
     Lista *cabeca; //head list 
     int tamanho; //amount of lists 
}; 
typedef struct vetorListas VetorListas; 

//This is the item to be inserted 

struct item 
{ 
     int id; //the ID used for the comparison of sort 
     char *nome; //just the name of it 
}; 
typedef struct item Item; 

在這個函數中使用其他功能和i找到列表,nomeDaList是一個字符串(字符*)是Item

void * 
insert(void * nomeDaLista, Item * i) 
{ 
    Lista * auxLista; //the list 
    auxLista = idl(nomeDaLista); //the function to get the list by it's name. It works, no worries. 


    //down here, is the sequence of codes translated to my program (got by the website I showed before) 

    No * temp = auxLista->cabeca; 
    No * prev = NULL; 
    No * ptr; 

    Item * itemTemp; 
    itemTemp = temp->item; 

    ptr = criaNo(i); //this function creates (makes the malloc and all) a node (No) and return the created node. 



    if(temp == NULL) 
    { 
     ptr->prox=NULL; 
     auxLista->cabeca = ptr; 
     return auxLista; 
    } 

    if(i->id < itemTemp->id) 
    { 
     ptr->prox = auxLista->cabeca; 
     auxLista->cabeca = ptr; 
     return auxLista; 
    } else 
    { 
     while(temp != NULL) 
     { 
      if(i->id > itemTemp->id) 
      { 
       prev = temp; 
       temp = temp->prox; 
       continue; 
      } else 
      { 
       prev->prox = ptr; 
       ptr->prox = temp; 
       return auxLista; 
      } 
     } 

     prev->prox = ptr; 
    } 
}  

請幫助這個分段錯誤(核心轉儲)。

+0

'if(temp == NULL)':您已經在'itemTemp = temp-> item;'處使用了'temp'。 – BLUEPIXY

+0

..你會看到如果你使用過你的調試器:( –

+0

所以,我應該評論如果(臨時== NULL)嗎?還是不知道該怎麼辦......我很抱歉,我沒有IDE和我不知道如何處理gdd –

回答

0

你必須檢查在這一行
if(temp == NULL)
即應,通常會,保護您免受段錯誤從通過NULL指針訪問。
但是,在幾行之前,您已經取消引用了temp兩次。
itemTemp = temp->item;

No * temp = auxLista->cabeca;

你應該改變的代碼,以確保這些線路只有得到執行,如果TMP非NULL。例如。拆分變量定義及其初始化,並在檢查行之後移動init。

您還會收到一個函數criaNo(i)的指針,並在稍後使用它幾行,而不是根據NULL檢查它。
ptr->prox=NULL;
目前還不清楚,是否保證爲非NULL。你將不得不使用「橡皮鴨」功能,即詳細檢查它是否可以返回NULL。

這裏是一個很好的描述如何調試(主要)沒有調試器,也解釋了「橡膠鴨」。 https://ericlippert.com/2014/03/05/how-to-debug-small-programs/

爲了您不知道如何使用調試器的問題:
How to debug using gdb?

爲了您不使用IDE的問題:
找到一個,救疼痛。
我最喜歡的搜索引擎爲我的當前使用的免費IDE提供(用於「免費IDE c」)作爲第一匹配,我正在考慮將其轉換爲第三匹配。