2015-05-23 88 views
-1

我寫了一個函數在C中導致內存錯誤的順序鏈接列表?

void 
insertNode(node_t *front, node_t *nodeIn) { 
    node_t *currentNode = front; 
    node_t *copy; 
    if (!(copy = (node_t*)malloc(sizeof(struct node)))) { 
     printf("Out of memory, exiting here?"); 
     exit(0); 
    } 
    strcpy(copy->name, nodeIn->name); 
    copy->aisle = nodeIn->aisle; 
    copy->shelf = nodeIn->shelf; 
    copy->mass = nodeIn->mass; 
    copy->price = nodeIn->price; 
    copy->quantity = nodeIn->quantity; 
    copy->next = NULL; 

    if (front == NULL || strcmp(front->name,copy->name) > 0) { 
     copy->next = currentNode; 
     front = copy; 
     printf("%s\n", front->name); 
    } 
    else { 
     while (currentNode->next != NULL && 
      strcmp((currentNode->next)->name,copy->name) < 0) { 
      currentNode = currentNode->next; 
     } 
     copy->next = currentNode->next; 
     currentNode->next = copy; 
    } 
} 

它接受一個指向前面節點和我想插入到列表中的節點,但按預期不起作用。我的代碼中是否有任何明顯的問題可以突破?

+1

'前面=拷貝;'不*不*呼叫者的傳入的指針'front'。呼叫者的指針保持不變。該問題本質上*相同* [對**這個問題](https://stackoverflow.com/questions/26834117/insert-for-singly-linked-list-c?rq=1),在列表中找到在這個頁面的右側,雖然有更好的方法來解決這個問題。 – WhozCraig

+3

歡迎來到SO。你是什​​麼意思_「它沒有按預期運行」_?你有沒有得到一個特定的錯誤信息或類似的東西?如果是,請將其添加到您的問題。 – luator

+0

在我的程序的另一個地方,有一個'Exiting,out of memory'語句,如果我註釋掉這個函數不會觸發,所以我認爲這裏一定有什麼問題。 – WillJustWill

回答

1
/** 
* @param front Might be changed upon insertion in front 
* @param nodeIn payload to insert; will neither be changed, 
*    nor used in the list 
*/ 
void 
insertNode(node_t **front, node_t *nodeIn) { 
    node_t *copy; 
    if (!(copy = (node_t*)malloc(sizeof(node_t)))) { 
     printf("Out of memory, exiting here?"); 
     exit(0); 
    } 
    copy->name = strdup(nodeIn->name); 
    copy->aisle = nodeIn->aisle; 
    copy->shelf = nodeIn->shelf; 
    copy->mass = nodeIn->mass; 
    copy->price = nodeIn->price; 
    copy->quantity = nodeIn->quantity; 

    node_t **currentNode = front; 
    while (*currentNode != NULL && strcmp((*currentNode)->name, copy->name) < 0) { 
     currentNode = &(*currentNode)->next; 
    } 
    copy->next = *currentNode; 
    *currentNode = copy; 
} 
  • front指針是在出參數,因爲它可能在前面插入時被改變。
  • name未分配,strdup使字符串重複。
  • currentNode是別名。它允許更改前面的變量或下一個字段。
  • wile-loop將currentNode定位在正確的變量上。

刪除也應該是免費的名字。

用法:

node_t *list = NULL; 
node_t data; 

data.name = "unu"; 
... 
insertNode(&list, &data); 
data.name = "du"; 
... 
insertNode(&list, &data); 
data.name = "tri"; 
... 
insertNode(&list, &data); 
+0

'strcmp((* currentNode) - > next-> name,copy-> name)<0){'currentnode-> next在這裏可能爲NULL ... – joop

+0

@joop too:thanks,copy error,original code working 'node_t * - > next'。 –