linux实用技巧用valgrind做内存检查(内存泄露等)
来源: 作者: 发布时间:2007-10-09
==4270==
==4270== Invalid write of size 1
==4270== at 0x400619C: strcpy (mc_replace_strmem.c:271)
==4270== by 0x80483DB: main (test.c:8)
==4270== Address 0x4023033 is 1 bytes after a block of size 10 alloc'd
==4270== at 0x40044F6: malloc (vg_replace_malloc.c:149)
==4270== by 0x80483C5: main (test.c:7)
==4270==
==4270== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 12 from 1)
==4270== malloc/free: in use at exit: 10 bytes in 1 blocks.
==4270== malloc/free: 1 allocs, 0 frees, 10 bytes allocated.
==4270== For counts of detected errors, rerun with: -v
==4270== searching for pointers to 1 not-freed blocks.
==4270== checked 51,496 bytes.
==4270==
==4270==
==4270== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4270== at 0x40044F6: malloc (vg_replace_malloc.c:149)
==4270== by 0x80483C5: main (test.c:7)
==4270==
==4270== LEAK SUMMARY:
==4270== definitely lost: 10 bytes in 1 blocks.
==4270== possibly lost: 0 bytes in 0 blocks.
==4270== still reachable: 0 bytes in 0 blocks.
==4270== suppressed: 0 bytes in 0 blocks.
==4270== Reachable blocks (those to which a pointer was found) are not shown.
==4270== To see them, rerun with: --show-reachable=yes
从这份报告可以看出,进程号是4270,test.c的第8行写内存越界了,引起写内存越界的是strcpy函数,
第7行泄漏了10个字节的内存,引起内存泄漏的是malloc函数。
例子二(test2.c)
#include <stdio.h>
int foo(int x)
{
if (x < 0) {
printf("%d ", x);
}
return 0;
}
int main(int argc, char *argv[])
{
int x;
foo(x);
return 0;
}
编译程序
gcc -g -o test2 test2.c
用valgrind做内存检查
valgrind --tool=memcheck ./test2
输出报告如下
==4285== Memcheck, a memory error detector.
==4285== Copyright (C) 2002-2006, and GNU GPL'd, by Julian Seward et al.
如果你想咨询课程、学费、就业、开班等情况!请拨打我们的咨询热线0371-66252525 ! 或者点击QQ、右侧的图标与我们在线老师咨询!











