c++ - Valgrind错误链表

标签 c++ linked-list valgrind

我正在做作业,对输出的所有测试都运行良好。但我总是收到这个 Valgrind 错误:

==22990== Memcheck, a memory error detector
==22990== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==22990== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==22990== Command: ./a.out
==22990== Parent PID: 22989
==22990== 
==22990== Invalid read of size 8
==22990==    **at 0x401DFB: IntList::removeAll() (IntList.cpp:113**)
==22990==    by 0x40113F: main (main.cpp:120)
==22990==  Address 0x4c50248 is 8 bytes inside a block of size 16 free'd
==22990==    at 0x4A05FD6: operator delete(void*) (vg_replace_malloc.c:480)
==22990==    **by 0x401DF6: IntList::removeAll() (IntList.cpp:117)**
==22990==    by 0x40113F: main (main.cpp:120)
==22990== 
==22990== 
==22990== HEAP SUMMARY:
==22990==     in use at exit: 0 bytes in 0 blocks
==22990==   total heap usage: 2,009 allocs, 2,009 frees, 40,128 bytes allocated
==22990== 
==22990== All heap blocks were freed -- no leaks are possible
==22990== 
==22990== For counts of detected and suppressed errors, rerun with: -v
==22990== ERROR SUMMARY: 6 errors from 1 contexts (suppressed: 6 from 6)

所以它告诉我我的 removeall() 函数正在泄漏内存,对吗?错误消息谈到第 113 和 117 行。113 是 while 循环开始的行,117 是 delete temp。

removeall() 函数:

void IntList::removeAll()
{
    NodePtr temp;
    temp = head;
    if(head == NULL){
        cout << "The list is empty" << endl;
        return;
    }

    while (temp-> link != NULL)
    {
            temp = head;
        head = temp->link;
        delete temp;
    }

}

somoene 可以帮我解决这个问题吗?我是否正确理解了 valgrind 错误?我该如何修复内存泄漏?

抱歉,如果之前有人问过这个问题。我尝试了搜索功能,但没有成功。

最佳答案

很容易看出,在上一次迭代结束时将 temp 删除后,您将在循环条件中取消引用它。您也在删除最后一个元素之前停止。你想要更像的东西

while (NodePtr temp = head) {
    head = temp->link;
    delete temp;
}

如果列表为空,这也会正确运行,因此无需事先检查,除非您特别想在这种情况下打印一些东西。

关于c++ - Valgrind错误链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21531705/

相关文章:

c - 我不明白为什么我会收到这个 valgrind 错误

c - strcastr 中的读取大小无效

c++ - std::cout 到 QTextBrowser

c++ - 具有算术运算返回类型的 valarray

c - C 中的链表太慢

C 移位插入链表

c++ - 有没有办法在 C++ 基类中创建 "virtual"变量?

c++ - C++ 中迭代器的前缀和后缀增量运算符重载实现之间的区别

c - 使用链表实现堆栈的意外结果

c++ - 免费(): invalid next size (fast) in Cpp