$ gcc -Wall test1.c -g -o test1
$ valgrind --tool=memcheck --leak-check=full ./test1
==3391== Memcheck, a memory error detector.
==3391== Copyright (C) 2002-2008, and GNU GPL'd, by Julian Seward et al.
==3391== Using LibVEX rev 1878, a library for dynamic binary translation.
==3391== Copyright (C) 2004-2008, and GNU GPL'd, by OpenWorks LLP.
==3391== Using valgrind-3.4.0, a dynamic binary instrumentation framework.
==3391== Copyright (C) 2000-2008, and GNU GPL'd, by Julian Seward et al.
==3391== For more details, rerun with: -v
==3391==
==3391==
==3391== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 3 from 1)
==3391== malloc/free: in use at exit: 40 bytes in 1 blocks.
==3391== malloc/free: 1 allocs, 0 frees, 40 bytes allocated.
==3391== For counts of detected errors, rerun with: -v
==3391== searching for pointers to 1 not-freed blocks.
==3391== checked 57,196 bytes.
==3391==
==3391== LEAK SUMMARY:
==3391== definitely lost: 0 bytes in 0 blocks.
==3391== possibly lost: 0 bytes in 0 blocks.
==3391== still reachable: 40 bytes in 1 blocks.
==3391== suppressed: 0 bytes in 0 blocks.
==3391== Reachable blocks (those to which a pointer was found) are not shown.
==3391== To see them, rerun with: --leak-check=full --show-reachable=yes
我们可以看到没有内存泄露。
$ gcc -Wall test2.c -g -o test2
$ valgrind --tool=memcheck --leak-check=full ./test2
gcc -Wall 1.c -g -o test2
~/20090212$ valgrind --tool=memcheck --leak-check=full test2
==3479== Memcheck, a memory error detector.
==3479== Copyright (C) 2002-2008, and GNU GPL'd, by Julian Seward et al.
==3479== Using LibVEX rev 1878, a library for dynamic binary translation.
==3479== Copyright (C) 2004-2008, and GNU GPL'd, by OpenWorks LLP.
==3479== Using valgrind-3.4.0, a dynamic binary instrumentation framework.
==3479== Copyright (C) 2000-2008, and GNU GPL'd, by Julian Seward et al.
==3479== For more details, rerun with: -v
==3479==
succeed exit!==3479==
==3479== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 3 from 1)
==3479== malloc/free: in use at exit: 40 bytes in 1 blocks.
==3479== malloc/free: 1 allocs, 0 frees, 40 bytes allocated.
==3479== For counts of detected errors, rerun with: -v
==3479== searching for pointers to 1 not-freed blocks.
==3479== checked 57,196 bytes.
==3479==
==3479== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3479== at 0x4021B38: malloc (vg_replace_malloc.c:207)
==3479== by 0x8048435: f (1.c:9)
==3479== by 0x8048472: main (1.c:21)
==3479==
==3479== LEAK SUMMARY:
==3479== definitely lost: 40 bytes in 1 blocks.
==3479== possibly lost: 0 bytes in 0 blocks.
==3479== still reachable: 0 bytes in 0 blocks.
==3479== suppressed: 0 bytes in 0 blocks.
我们可以看到有内存泄露。
通过上面的例子,可以了解到:malloc系统函数分配的内存最好要自己释放,以免内存泄露。