gpt4 book ai didi

c++ - Valgrind错误链表

转载 作者:行者123 更新时间:2023-11-28 02:58:09 26 4
gpt4 key购买 nike

我正在做作业,对输出的所有测试都运行良好。但我总是收到这个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com