简体   繁体   English

我不明白我在取消分配内存时做错了什么

[英]I don't understand what I'm doing wrong with my de-allocation of memory

So I have a linked list getting created correctly, linked properly but when I try to de-allocate memory I can't seem to delete any node, the list still exists.所以我有一个正确创建的链接列表,链接正确,但是当我尝试取消分配内存时,我似乎无法删除任何节点,该列表仍然存在。 Code for my list deconstructor:我的列表解构器的代码:

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();
}

And my user class has this for the vars and deconstructor:我的用户类为 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?
}

The code as written now only has one serious flaw;现在编写的代码只有一个严重缺陷; you delete the list chained to head , but never set head to NULL .您删除链接到head的列表,但永远不要将 head 设置为NULL Anyone touching it from this point on is hitting undefined behavior through a garbage pointer.从这一点开始接触它的任何人都会通过垃圾指针来达到未定义的行为。

Set head to NULL if you're wiping the list like this.如果您像这样擦除列表,请将 head 设置为 NULL。 Alternatively, since you know head should be NULL after this is done anyway, forego using currentNode at all.或者,由于您知道无论如何完成此操作后head都应该为NULL ,因此完全放弃使用currentNode Simply use head itself as the pointer that is walking the list.只需使用head本身作为遍历列表的指针。 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.此外,在您的析构函数中不需要按原样检查 ( head == NULL )。 It is already checked in your free_memory() function, as it should be.它已经在您的free_memory()函数中进行了检查,应该如此。

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.像聪明人一样使用智能指针,让程序像一个想为自己的手艺赚钱的人一样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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