Double Linked List Crashing After Appending Node

旧巷老猫 提交于 2021-02-08 10:42:18

问题


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

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.


回答1:


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.

So it should be

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.



来源:https://stackoverflow.com/questions/60821005/double-linked-list-crashing-after-appending-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!