gpt4 book ai didi

c - 如何释放内存到c中的指针

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:02 24 4
gpt4 key购买 nike

我有这个(错误的)代码

void function(deq** dq, int data)
{
// TODO: add a new element at the end of the queue
deq *temp = (dequeue*)malloc(sizeof(dequeue));
deq *copy = (*dq);
temp->data = data;


if (copy == NULL) {
temp->next = NULL;
temp->prev = NULL;
(*dq) = temp;
}
else{
while (copy->next != NULL) {
copy = copy->next;
}

temp->prev = copy;
temp->next = NULL;
copy->next = temp;
(*dq) = temp;
}

//free(temp);
}

我的问题是我无法在不使程序崩溃的情况下释放临时文件,有没有办法解决这个问题?有人能告诉我为什么当我免费使用这个程序时我无法运行该程序但是使用 valgrind 它可以工作......太有趣了。

==17186== HEAP SUMMARY:
==17186== in use at exit: 216 bytes in 9 blocks
==17186== total heap usage: 15 allocs, 6 frees, 360 bytes allocated
==17186==
==17186== 72 (24 direct, 48 indirect) bytes in 1 blocks are definitely lost in loss record 8 of 9
==17186== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17186== by 0x400670: dequeue_push_front (dequeue.c:12)
==17186== by 0x400A1D: main (main.c:21)
==17186==
==17186== 144 (24 direct, 120 indirect) bytes in 1 blocks are definitely lost in loss record 9 of 9
==17186== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17186== by 0x400670: dequeue_push_front (dequeue.c:12)
==17186== by 0x400BA3: main (main.c:48)
==17186==
==17186== LEAK SUMMARY:
==17186== definitely lost: 48 bytes in 2 blocks
==17186== indirectly lost: 168 bytes in 7 blocks
==17186== possibly lost: 0 bytes in 0 blocks
==17186== still reachable: 0 bytes in 0 blocks
==17186== suppressed: 0 bytes in 0 blocks
==17186==
==17186== For counts of detected and suppressed errors, rerun with: -v
==17186== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

最佳答案

您不想在此函数中free(temp)

此函数使用malloc 在堆上分配temp,然后将节点放入列表中。如果您 free() 您刚刚在此处分配的内存,您将在列表中留下一个指向无效内存的节点。引用该节点会导致未定义的行为,在本例中会出现在核心转储中。

调用 free() 的适当时间是从列表中删除节点时。

至于内存泄漏,它发生在 else block 中。

您将 temp 放在列表的末尾,但随后用 temp 覆盖了列表的头部,因此您对列表其余部分的唯一引用是在 tempprev 指针中。然而,由于现在这是你的新头,你可能不会在清理时费心去查看 prev 。所以你有内存泄漏。

要修复漏洞,去掉对*dq的赋值:

...
else {
while (copy->next != NULL) {
copy = copy->next;
}

temp->prev = copy;
temp->next = NULL;
copy->next = temp;
}
...

关于c - 如何释放内存到c中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049588/

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