首页 > 解决方案 > 是什么导致双向链表中附加节点函数出现分段错误?

问题描述

我的双向链表实现如下,每个节点保存一个包含四个值的数组

#define EMPTYNODE 0

struct node {
short data[4]; // pay attention
struct node* next;
struct node* prev;
};

typedef struct node nodeQ_t;

typedef enum{
   LIST_FALSE = 0,
   LIST_TRUE = 1,
} status_t;

nodeQ_t* createNode(short values[4]){

    nodeQ_t* node = (nodeQ_t*)malloc(sizeof(node));
    for(int i=0; i < 4; i++){
       node->data[i] = values[i];
     }

   node->next = EMPTYNODE;
   node->prev = EMPTYNODE;
   return node;
}

现在我正在尝试以一种方式编写附加函数,即我提供它的头部和在 createNode 函数中创建的节点,以便它将它附加到列表中......但它会产生分段错误......

status_t appendNode(nodeQ_t* head, nodeQ_t* newNode){
if(head == EMPTYNODE || newNode == EMPTYNODE){
    return LIST_FALSE;
};

nodeQ_t* currentNode = head;

while(currentNode != EMPTYNODE){
    if(currentNode->next == EMPTYNODE){ //it means that current node is tail
        currentNode->next = newNode;  //segmenttion fault arises at exactly this line 
        newNode->prev = currentNode;
    }
    currentNode = currentNode->next;
}
return LIST_TRUE;
}

请让我知道这是什么原因...供您参考,我的主要功能是

int main(){
  short array[4] = {1,2,3,4};

  nodeQ_t* head  = createNode(array);

  printList(head);


  short array2[4] = {5,6,7,8};

  nodeQ_t* newNode = createNode(array2);

  appendNode(head, newNode);


  printList(head);



  return 0;

}

如果您需要任何进一步的信息或解释,请告诉我

标签: cdata-structureslinked-listappenddoubly-linked-list

解决方案


break如评论中所述,一旦到达终点,您就需要退出循环:

while(currentNode != EMPTYNODE) {
    if (currentNode->next == EMPTYNODE) {
        currentNode->next = newNode;
        newNode->prev = currentNode;
        // need a break here
    }
    currentNode = currentNode->next;
    // When at the end of the list the 1st time through, 
    // currentNode is the newly created node because you have
    //     currentNode->next = newNode
    // then
    //     currentNode = currentNode->next
    // On the next iteration, the new node next ends up getting pointed to itself 
    // since on that iteration newNode and currentNode are the same.
    // and you end up with an infinite loop.
}

另一种选择是循环currentNode->next

while (currentNode->next) {
    currentNode = currentNode->next;
}
currentNode->next = newNode;
newNode->prev = currentNode;

我应该注意到这是有效的,因为您之前确保currentNode不是NULL.

另外,您在这里的分配是错误的:

nodeQ_t* node = (nodeQ_t*)malloc(sizeof(node));

因为node是指针,sizeof(node)是指针的大小,而不是struct node. 应该

nodeQ_t* node = (nodeQ_t*)malloc(sizeof(*node));

推荐阅读