linux实用技巧用valgrind做内存检查(内存泄露等)
来源: 作者: 发布时间:2007-10-09
==4187== For counts of detected errors, rerun with: -v
==4187== searching for pointers to 105 not-freed blocks.
==4187== checked 145,292 bytes.
==4187==
==4187== LEAK SUMMARY:
==4187== definitely lost: 0 bytes in 0 blocks.
==4187== possibly lost: 0 bytes in 0 blocks.
==4187== still reachable: 15,154 bytes in 105 blocks.
==4187== suppressed: 0 bytes in 0 blocks.
==4187== Reachable blocks (those to which a pointer was found) are not shown.
==4187== To see them, rerun with: --show-reachable=yes
这里的“4187”指的是执行ls -l的进程ID,这有利于区别不同进程的报告。memcheck会给出报告,分配置和释放了多少内存,有多少内存泄漏了,还有多少内存的访问是可达的,检查了多少字节的内存。
下面举两个用valgrind做内存检查的例子
例子一 (test.c):
#include <string.h>
int main(int argc, char *argv[])
{
char *ptr;
ptr = (char*) malloc(10);
strcpy(ptr, "01234567890");
return 0;
}
编译程序
gcc -g -o test test.c
用valgrind执行命令
valgrind --tool=memcheck --leak-check=yes ./test
报告如下
==4270== Memcheck, a memory error detector.
==4270== Copyright (C) 2002-2006, and GNU GPL'd, by Julian Seward et al.
==4270== Using LibVEX rev 1606, a library for dynamic binary translation.
==4270== Copyright (C) 2004-2006, and GNU GPL'd, by OpenWorks LLP.
==4270== Using valgrind-3.2.0, a dynamic binary instrumentation framework.
==4270== Copyright (C) 2000-2006, and GNU GPL'd, by Julian Seward et al.
==4270== For more details, rerun with: -v
==4270==
==4270== Invalid write of size 1
==4270== at 0x4006190: strcpy (mc_replace_strmem.c:271)
==4270== by 0x80483DB: main (test.c:8)
==4270== Address 0x4023032 is 0 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)
如果你想咨询课程、学费、就业、开班等情况!请拨打我们的咨询热线0371-66252525 ! 或者点击QQ、右侧的图标与我们在线老师咨询!











