char *p = malloc(100);
if (p != 0)
{
p += 50;
/* at this point, no pointer points to the start of the allocated memory */
/* however, it is still accessible */
for (int i = -50; i != 50; i++)
p[i] = 1;
free (p - 50);
}
因为它看起来很有趣,所以我确实运行了代码并且valgrind它。结果如下。
[email protected]:~$ valgrind test
==14735== Memcheck, a memory error detector
==14735== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==14735== Using Valgrind-3.6.1-Debian and LibVEX; rerun with -h for copyright info
==14735== Command: test
==14735==
==14735==
==14735== HEAP SUMMARY:
==14735== in use at exit: 0 bytes in 0 blocks
==14735== total heap usage: 32 allocs, 32 frees, 2,017 bytes allocated
==14735==
==14735== All heap blocks were freed -- no leaks are possible
==14735==
==14735== For counts of detected and suppressed errors, rerun with: -v
==14735== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 6)
它说没有泄漏是可能的。我错过了什么?
请将评论作为评论,而不是答案。 StackOverflow通知用户对他们答案的评论,但不会(也不应该)通知也回答同一问题的其他用户的用户。这说... – hvd 2012-07-31 14:17:42
...代码最终释放了内存,所以valgrind没有看到它。我所做的一点是,如果程序在到达'free'之前退出(或者完全没有释放),并且'p'保持设置,那么valgrind会认为分配的内存可能会丢失。在测试时,为了让“p”保持设置,您可能还需要将“p”设置为全局。 – hvd 2012-07-31 14:20:09
我试图发表评论,但评论有字符数限制。对于那个很抱歉。 – jaeyong 2012-08-01 00:42:28