追加节点后双链表崩溃 [英] Double Linked List Crashing After Appending Node

查看:52
本文介绍了追加节点后双链表崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C实现一个双向链接列表,并且每当我尝试将第三个节点添加到列表时都遇到崩溃.我在程序崩溃的那一行中找到了代码,但是由于代码看起来安全",所以我不明白为什么.我没有从编译器收到任何警告或错误.如果有人能够解释可能的指针错误或崩溃背后的原因,将不胜感激.看到与我的代码相关的任何问题或疑虑,我都会立即回答.

I am trying to achieve a double linked list using C and have encountered a crash whenever I try to append a third node to my list. I have located the line in my code in which my program crashes, but I cannot understand why since the code looks "safe". I have received no warnings or errors from the compiler. If anyone is able to explain a possible pointer error or the reason behind the crash, it would be much appreciated. Any questions or concerns related to my code will be answered as soon as I see them.

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"中使用的头指针后,它将返回一个新地址或相同的地址.每当我附加前两个节点时,该代码就可以正常运行,但是在尝试附加第三个节点时,该代码就会崩溃.

The code presented above is a function that appends a new node to the list. It returns a new address or same address back when finished to update the head pointer used in 'main'. The code runs functionally whenever I append the first two nodes, but crashes whenever it tries to append a third node.

推荐答案

您分配的内存空间量是指向结构节点的指针的大小,不是您想要的 struct节点的实际大小.

The amount of memory space you are allocating is the size of a pointer to a struct node, not the actual size of a struct node - which you want.

应该是

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

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

As a consequence of allocating insufficient memory, your program is writing outside the memory block that it allocated, which causes undefined behavior. This means that anything can happen. For example, the program may crash immediately, not at all, or at a later time.

这篇关于追加节点后双链表崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆