我正在尝试使用C实现一个双链表,并且每当我尝试将第三个节点添加到列表时都遇到崩溃。我在程序崩溃的那一行中找到了代码,但是由于代码看起来“安全”,所以我不明白为什么。我没有从编译器收到任何警告或错误。如果有人能够解释可能的指针错误或崩溃背后的原因,将不胜感激。看到与我的代码相关的任何问题或疑虑,我将立即回答。
struct node *appendNode(struct node *headRef, unsigned short int newData) {
struct node *newNode = (struct node*)malloc(sizeof(struct node*));
newNode->data = newData;
newNode->next = NULL;
if(headRef == NULL) { //list is empty and returns the newNode to become the head pointer
newNode->previous = NULL;
return newNode;
} else { //list is not empty and newNode is appended to end of list ----(Area of crash)----
struct node *current = headRef;
while(current->next != NULL) {
current = current->next;
}
current->next = newNode;
newNode->previous = current;
return headRef;
} //----------------------------------------------------------------------------------
};
上面提供的代码是将新节点追加到列表的函数。完成更新“ main”中使用的头指针后,它将返回一个新地址或相同的地址。每当我附加前两个节点时,该代码就可以正常运行,但是在尝试附加第三个节点时,该代码就会崩溃。
您正在分配的内存空间量是[struct node
的指针的大小,而不是您想要的struct node
的实际大小。
struct node *newNode = (struct node*)malloc(sizeof(struct node));
由于分配的内存不足,您的程序正在其分配的内存块外部写入,这导致undefined behavior。这意味着任何事情都可能发生。例如,该程序可能立即崩溃,而不是根本崩溃,或者稍后崩溃。