繁体   English   中英

追加节点后双链表崩溃

[英]Double Linked List Crashing After Appending Node

我正在尝试使用 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));

由于分配的内存不足,您的程序将写入它分配的内存块之外,这会导致未定义的行为 这意味着任何事情都可能发生。 例如,程序可能会立即崩溃,根本不会崩溃,或者稍后崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM