C - 无法释放双向链表节点

时间:2016-05-28 18:45:34

标签: c free doubly-linked-list

我有这样的数据结构:

typedef struct telephoneBookNode
{
    int id;
    char name[NAME_LENGTH];
    char telephone[TELEPHONE_LENGTH];
    struct telephoneBookNode * previousNode;
    struct telephoneBookNode * nextNode;
} TelephoneBookNode;

typedef struct telephoneBookList
{
    TelephoneBookNode * head;
    TelephoneBookNode * tail;
    TelephoneBookNode * current;
    unsigned size;
} TelephoneBookList;

我可以创建节点,并使List包含数据,因为我在显示List,插入或移动节点时没有任何问题....

但是当我写函数来擦除List时,我收到了错误:

PhoneBook(6187,0x7fff77045000) malloc: *** error for object 0x7f87c1f00004: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

这是我的橡皮擦功能:

void freeTelephoneBookList(TelephoneBookList* aList) {
    TelephoneBookNode* node;
    TelephoneBookNode* temp = aList->head;

    while (temp) {
        node = temp;
        temp = node->nextNode;
        freeTelephoneBookNode(node);
    }
    free(aList);
}

void freeTelephoneBookNode(TelephoneBookNode * node) {
    free(node->name);
    free(node->telephone);
    free(node);
}

请有人告诉我这里我做错了什么。谢谢!

1 个答案:

答案 0 :(得分:2)

注意此答案与问题的initial version有关。

变量node->namenode->telephone指向单独分配的内存块的指针,它们只是*node的一部分。将freeTelephoneBookNode函数减少为

void freeTelephoneBookNode(TelephoneBookNode * node) {
    free(node);
}