追加节点后双链表崩溃

Double Linked List Crashing After Appending Node

我正在尝试使用 C 实现双链表,但每当我尝试将第三个节点附加到我的列表时遇到崩溃。我在我的代码中找到了我的程序崩溃的行,但我不明白为什么因为代码看起来 "safe"。我没有收到来自编译器的警告或错误。如果有人能够解释可能的指针错误或崩溃背后的原因,我们将不胜感激。与我的代码相关的任何问题或疑虑将在我看到它们后立即得到解答。

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;
     }       //----------------------------------------------------------------------------------
 };

上面给出的代码是一个将新节点附加到列表的函数。 returns 完成更新 'main' 中使用的头指针后返回一个新地址或相同地址。每当我追加前两个节点时,代码都能正常运行,但每当它尝试追加第三个节点时就会崩溃。

您分配的内存量 space 是指向 的指针的大小 struct node,而不是 [=11] 的实际大小=] - 你想要的。

所以应该是

struct node *newNode = (struct node*)malloc(sizeof(struct node));

由于分配的内存不足,您的程序正在其分配的内存块之外写入,这会导致 undefined behavior。这意味着任何事情都可能发生。例如,程序可能会立即崩溃、根本不会崩溃或稍后崩溃。