【发布时间】:2016-10-14 18:12:07
【问题描述】:
我有这个(坏的)代码
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);
}
我的问题是我无法在不使程序崩溃的情况下释放 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)
【问题讨论】:
-
为什么你们都通过
*dq输出地址,并在函数结束时释放它? -
我知道免费是不好的,但如果我把它注释掉,那么我就会得到那些内存泄漏
-
free不错不好。这是你应该做的清理自己的事情。它只需要正确完成。