简体   繁体   中英

Destroying a Doubly Linked List in C

The purpose of this function in the code below, which passes in a doubly linked list, is to take the nodes in the list one by one and free() them. But every time I try to debug my program. It gives me this message: "Exception thrown: read access violation. currNode was nullptr." I am having trouble making sense of this in my code, what am I doing wrong or am missing that is causing this?

void DListDestruct(DList* list) {
DListNode* currNode;
DListNode* next;

currNode = (DListNode*)malloc(sizeof(DListNode));
currNode = list->head;

if (currNode == NULL) {
    return;
}


while (list->head != NULL) {

    next = currNode->next;
    free(currNode);
    currNode = (DListNode*)malloc(sizeof(DListNode));
    currNode = next;

}

list->head = NULL;

return;
}

Your loop is testing list->head , which the body of the loop never changes. Since currNode is what gets freed, that is probably what you should be checking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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