c - 是什么导致双向链表中附加节点函数出现分段错误?
问题描述
我的双向链表实现如下,每个节点保存一个包含四个值的数组
#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;
}
如果您需要任何进一步的信息或解释,请告诉我
解决方案
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));
推荐阅读
- c# - 在哪里使用 Async Await 和数据库?在高级或低级模块中?
- python - 将具有不同列的 Pandas DataFrames 转换为可迭代并重组为一个 DataFrame
- oracle - Oracle:一个或多个脚本引发实例失败
- discord - 同时运行2个函数
- python - 为什么即使 InputData 不同,建模仍然有效?
- office-js - javascript Outlook 加载项的技术/平台建议
- php - 如何在 Laravel 的主刀片文件 Switch 语句中调用子刀片文件?
- javascript - 我的发送按钮没有向我的聊天框发送数据?它不起作用
- google-assistant-sdk - 我的 api 不会运行示例代码并且状态无法注册设备
- postgresql - 如何交换具有唯一且非空约束的外键引用?