gpt4 book ai didi

c++ - 我找不到 valgrind 告诉我的内存链接

转载 作者:搜寻专家 更新时间:2023-10-31 00:06:23 24 4
gpt4 key购买 nike

我正在编写一个链表和一个向其中添加新值的函数,这是我的代码:

    #include <iostream>

using namespace std;

struct ListNode {
int m_value;
ListNode *m_next;
ListNode () {}
ListNode(int i) {
m_value = i;
m_next = NULL;
}
};

void append(int const value, ListNode *head) {
ListNode *list = new ListNode(value);
if (head != NULL) {
while (head->m_next != NULL) {
head = head->m_next;
}
head->m_next = list;
} else {
head = list;
}
}

void print(ListNode *head) {
while (head != NULL) {
cout << head->m_value << endl;
head = head->m_next;
}
}

int main() {
ListNode *list = new ListNode(1);
append(2, list);
append(3, list);
append(4, list);
append(5, list);

print(list);

delete list;
}

然后我使用 valgrind 检查内存泄漏,使用这个命令:

    valgrind --leak-check=full --show-reachable=yes --trace-children=yes ./listnodes 

显示:

  64 (16 direct, 48 indirect) bytes in 1 blocks are definitely lost in loss record 4 of 4
at 0x4C3017F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
by 0x108B1D: append(int, ListNode*) (in /home/qihao/c/test/listnodes/listnodes/listnodes)
by 0x108968: main (in /home/qihao/c/test/listnodes/listnodes/listnodes)

LEAK SUMMARY:
definitely lost: 16 bytes in 1 blocks
indirectly lost: 48 bytes in 3 blocks
possibly lost: 0 bytes in 0 blocks
still reachable: 0 bytes in 0 blocks
suppressed: 0 bytes in 0 blocks

ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

有一处泄漏。我不知道我的代码中发生泄漏的地方,有人可以帮忙吗?谢谢。

最佳答案

因为您只删除了列表的头部。每次调用 append 函数时,您都会创建一个新节点。在你的程序结束时,你必须删除所有节点,尝试做这样的事情:

int main()
{
ListNode *list = new ListNode(1);
append(2, list);
append(3, list);
append(4, list);
append(5, list);

print(list);

ListNode *tmp1 = list;
ListNode *tmp2;
while (tmp1 != NULL)
{
tmp2 = tmp1->m_next;
delete tmp1;
tmp1 = tmp2;
}
}

关于c++ - 我找不到 valgrind 告诉我的内存链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58094363/

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