Chinaunix首页 | 论坛 | 博客
  • 博客访问: 134433
  • 博文数量: 51
  • 博客积分: 2500
  • 博客等级: 少校
  • 技术积分: 540
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-21 12:33
文章分类

全部博文(51)

文章存档

2011年(1)

2010年(5)

2009年(1)

2008年(12)

2007年(32)

我的朋友

分类:

2010-12-24 10:56:11

Valgrind是一个在Linux下运行,用在程序内存调试免费软件(GPL)。它可以被用来监视的程序运行中内存使用的情况,比如C 语言中的malloc和free或者 C++中的new和 delete。这个工具非常强大,本文的例子主要永在内存调试上

示例:
#include
#include
int main()
{
  char *ptr = (char *) malloc(1024);
  ptr[1024] = 0;    =====>数组访问越界
  ptr = NULL;
                    =====>内存泄漏
}

gcc -o checker checker.c


then run valgrind:

valgrind --tool=memcheck ./checker

==27857== Memcheck, a memory error detector.
==27857== Copyright (C) 2002-2006, and GNU GPL'd, by Julian Seward et al.
==27857== Using LibVEX rev 1658, a library for dynamic binary translation.
==27857== Copyright (C) 2004-2006, and GNU GPL'd, by OpenWorks LLP.
==27857== Using valgrind-3.2.1, a dynamic binary instrumentation framework.
==27857== Copyright (C) 2000-2006, and GNU GPL'd, by Julian Seward et al.
==27857== For more details, rerun with: -v
==27857==
==27857== Invalid write of size 1                        ======> 数组访问越界
==27857==    at 0x4004F8: main (checker.c:6)
==27857==  Address 0x4C30430 is 0 bytes after a block of size 1,024 alloc'd
==27857==    at 0x4A05809: malloc (vg_replace_malloc.c:149)
==27857==    by 0x4004E9: main (checker.c:5)
==27857==
==27857== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 1)
==27857== malloc/free: in use at exit: 1,024 bytes in 1 blocks.
==27857== malloc/free: 1 allocs, 0 frees, 1,024 bytes allocated.  ======>内存泄漏
==27857== For counts of detected errors, rerun with: -v
==27857== searching for pointers to 1 not-freed blocks.
==27857== checked 63,824 bytes.
==27857==
==27857== LEAK SUMMARY:
==27857==    definitely lost: 1,024 bytes in 1 blocks.
==27857==      possibly lost: 0 bytes in 0 blocks.
==27857==    still reachable: 0 bytes in 0 blocks.
==27857==         suppressed: 0 bytes in 0 blocks.
==27857== Use --leak-check=full to see details of leaked memory.


阅读(439) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~