3

所以我有一个正确创建的链接列表,正确链接但是当我尝试取消分配内存时,我似乎无法删除任何节点,该列表仍然存在。我的列表解构器的代码:

void LL_User::free_memory() {
    // TODO
    LL_User_Node *currentNode;
    currentNode = head;
    while(currentNode) {
        LL_User_Node *temp = currentNode;
        currentNode = currentNode->next;
        delete temp;
    }
    //cout << "LL_User::free_memory() is not implemented yet.\n";
}

LL_User::~LL_User() {
    if(head == NULL) {
        return;
    }
    free_memory();
}

我的用户类为 vars 和 deconstructor 提供了这个:

User::User() {
    username = "";
    password = "";
    first_name = "";
    last_name = "";
    profile_pic_filename = "";
    birth_year = 0;
    birth_month = 0;
    birth_day = 0;
}

User::~User() {
    //Nothing placed in body because strings and ints are dealt with by OS?
}
4

2 回答 2

4

现在写的代码只有一个严重的缺陷;您删除了链接到 的列表head,但从未将 head 设置为NULL。从这一点开始接触它的任何人都会通过垃圾指针遇到未定义的行为。

Set head to NULL if you're wiping the list like this. Alternatively, since you know head should be NULL after this is done anyway, forego using currentNode at all. Simply use head itself as the pointer that is walking the list. Think about that for awhile and it will come to you.

Also, as-written the check for (head == NULL) is not needed in your destructor. It is already checked in your free_memory() function, as it should be.

于 2012-11-19T18:32:52.707 回答
-1

You're manually deallocating it, that's what you're doing wrong. Use a smart pointer like a wise man, have a program that works like a man who wants to get paid for his craft.

于 2012-11-19T18:35:50.677 回答