Valgrind错误链表

时间:2014-02-03 15:50:27

标签: 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是删除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错误?如何修复内存泄漏?

很抱歉,如果之前有人询问过。我没有运气就尝试了搜索功能。

2 个答案:

答案 0 :(得分:2)

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

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

如果列表为空,这也会正常运行,因此除非您特别想在这种情况下打印某些内容,否则无需事先检查。

答案 1 :(得分:0)

如果temp->linkNULL,则永远不会删除temp,因此列表中至少还有一个节点。

我认为你在功能结束时错过了delete head;