Chinaunix首页 | 论坛 | 博客
  • 博客访问: 535028
  • 博文数量: 142
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1452
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-12 16:28
文章分类

全部博文(142)

文章存档

2016年(10)

2015年(60)

2014年(72)

我的朋友

分类: C/C++

2014-08-12 17:15:44

mtrace是glibc自带的内存检测工具。使用步骤如下:
1.在要检测内存泄露代码的开始处调用mtrace() (在mcheck.h中声明)
2.在内存泄露代码的结束处调用muntrace() 
3.设置环境变量MALLOC_TRACE,内存信息将保存在这个变量所指的路径中
4.编译时必须带上-g.
5.用perl脚本mtrace来解析MALLOC_TRACE指向的文件

For example, 以下是一段申请内存后没有释放内存的C代码 (mtrace.c):
点击(此处)折叠或打开
  1. #include <stdlib.h>
  2.  int main(void) {
  3.       int *a;
  4.       a = malloc(sizeof(int));
  5.       return 0;
  6. }
采用mtrace检测后的代码如下:

点击(此处)折叠或打开

  1. #include <stdlib.h>
  2. #include <mcheck.h>
  3. int main(void) {
  4.     mtrace();
  5.     int *a;
  6.     a = malloc(sizeof(int));
  7.     muntrace();
  8.     return 0;
  9. }
一、设置环境变量:
export MALLOC_TRACE=malloc_trace.log 
二、编译代码: gcc -g mtrace.c -o mtrace.out-------------注意编译时必须带上-g选项
三、运行可执行文件
      ./mtrace.out
四、使用perl脚本mtrace将机器指令装换成易读的输出
      ./mtrace mtrace.out malloc_trace.log

linux:~/test/mtrace>./mtrace mtrace.out malloc_trace.log
Memory not freed:
-----------------
   Address     Size     Caller
0x012fe460      0x4  at /home/gwwu/test/mtrace/mtrace.c:6

从中可以明显看出mtrace.c文件的第6行内存申请后没有释放了。

附上perl脚本

点击(此处)折叠或打开

  1. #! /usr/bin/perl
  2. #eval "exec /usr/bin/perl -S $0 $*" if 0;
  3. # Copyright (C) 1997-2004, 2005, 2006, 2007 Free Software Foundation, Inc.
  4. # This file is part of the GNU C Library.
  5. # Contributed by Ulrich Drepper <drepper@gnu.org>, 1997.
  6. # Based on the mtrace.awk script.

  7. # The GNU C Library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.

  11. # The GNU C Library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.

  15. # You should have received a copy of the GNU Lesser General Public
  16. # License along with the GNU C Library; if not, write to the Free
  17. # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  18. # 02111-1307 USA.

  19. $VERSION = "2.7";
  20. $PACKAGE = "libc";
  21. $progname = $0;

  22. sub usage {
  23.     print "Usage: mtrace [OPTION]... [Binary] MtraceData\n";
  24.     print " --help print this help, then exit\n";
  25.     print " --version print version number, then exit\n";
  26.     print "\n";
  27.     print "For bug reporting instructions, please see:\n";
  28.     print ".\n"; exit 0;
  29. }

  30. # We expect two arguments:
  31. # #1: the complete path to the binary
  32. # #2: the mtrace data filename
  33. # The usual options are also recognized.

  34. arglist: while (@ARGV) {
  35.              if ($ARGV[0] eq "--v" || $ARGV[0] eq "--ve" || $ARGV[0] eq "--ver" ||
  36.                      $ARGV[0] eq "--vers" || $ARGV[0] eq "--versi" ||
  37.                      $ARGV[0] eq "--versio" || $ARGV[0] eq "--version") {
  38.                  print "mtrace (GNU $PACKAGE) $VERSION\n";
  39.                  print "Copyright (C) 2007 Free Software Foundation, Inc.\n";
  40.                  print "This is free software; see the source for copying conditions. There is NO\n";
  41.                  print "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n";
  42.                  print "Written by Ulrich Drepper \n";
  43.                  exit 0;
  44.              } elsif ($ARGV[0] eq "--h" || $ARGV[0] eq "--he" || $ARGV[0] eq "--hel" ||
  45.                      $ARGV[0] eq "--help") {
  46.                  &usage;
  47.              } elsif ($ARGV[0] =~ /^-/) {
  48.                  print "$progname: unrecognized option `$ARGV[0]'\n";
  49.                  print "Try `$progname --help' for more information.\n";
  50.                  exit 1;
  51.              } else {
  52.                  last arglist;
  53.              }
  54.          }

  55. if ($#ARGV == 0) {
  56.     $binary="";
  57.     $data=$ARGV[0];
  58. } elsif ($#ARGV == 1) {
  59.     $binary=$ARGV[0];
  60.     $data=$ARGV[1];

  61.     if ($binary =~ /^.*[\/].*$/) {
  62.         $prog = $binary;
  63.     } else {
  64.         $prog = "./$binary";
  65.     }
  66.     if (open (LOCS, "env LD_TRACE_LOADED_OBJECTS=1 $prog |")) {
  67.         while (<LOCS>) {
  68.             chop;
  69.             if (/^.*=> (.*) .(0x[0123456789abcdef]*).$/) {
  70.                 $locs{$1} = $2;
  71.             }
  72.         }
  73.         close (LOCS);
  74.     }
  75. } else {
  76.     die "Wrong number of arguments, run $progname --help for help.";
  77. }

  78. sub location {
  79.     my $str = pop(@_);
  80.     return $str if ($str eq "");
  81.     if ($str =~ /.*[[](0x[^]]*)]:(.)*/) {
  82.         my $addr = $1;
  83.         my $fct = $2;
  84.         return $cache{$addr} if (exists $cache{$addr});
  85.         if ($binary ne "" && open (ADDR, "addr2line -e $binary $addr|")) {
  86.             my $line = <ADDR>;
  87.             chomp $line;
  88.             close (ADDR);
  89.             if ($line ne '??:0') {
  90.                 $cache{$addr} = $line;
  91.                 return $cache{$addr};
  92.             }
  93.         }
  94.         $cache{$addr} = $str = "$fct @ $addr";
  95.     } elsif ($str =~ /^(.*):.*[[](0x[^]]*)]$/) {
  96.         my $prog = $1;
  97.         my $addr = $2;
  98.         my $searchaddr;
  99.         return $cache{$addr} if (exists $cache{$addr});
  100.         if ($locs{$prog} ne "") {
  101.             $searchaddr = sprintf "%#x", $addr - $locs{$prog};
  102.         } else {
  103.             $searchaddr = $addr;
  104.             $prog = $binary;
  105.         }
  106.         if ($binary ne "" && open (ADDR, "addr2line -e $prog $searchaddr|")) {
  107.             my $line = <ADDR>;
  108.             chomp $line;
  109.             close (ADDR);
  110.             if ($line ne '??:0') {
  111.                 $cache{$addr} = $line;
  112.                 return $cache{$addr};
  113.             }
  114.         }
  115.         $cache{$addr} = $str = $addr;
  116.     } elsif ($str =~ /^.*[[](0x[^]]*)]$/) {
  117.         my $addr = $1;
  118.         return $cache{$addr} if (exists $cache{$addr});
  119.         if ($binary ne "" && open (ADDR, "addr2line -e $binary $addr|")) {
  120.             my $line = <ADDR>;
  121.             chomp $line;
  122.             close (ADDR);
  123.             if ($line ne '??:0') {
  124.                 $cache{$addr} = $line;
  125.                 return $cache{$addr};
  126.             }
  127.         }
  128.         $cache{$addr} = $str = $addr;
  129.     }
  130.     return $str;
  131. }

  132. $nr=0;
  133. open(DATA, "<$data") || die "Cannot open mtrace data file";
  134. while (<DATA>) {
  135.     my @cols = split (' ');
  136.     my $n, $where;
  137.     if ($cols[0] eq "@") {
  138. # We have address and/or function name.
  139.         $where=$cols[1];
  140.         $n=2;
  141.     } else {
  142.         $where="";
  143.         $n=0;
  144.     }

  145.     $allocaddr=$cols[$n + 1];
  146.     $howmuch=hex($cols[$n + 2]);

  147.     ++$nr;
  148. SWITCH: {
  149.             if ($cols[$n] eq "+") {
  150.                 if (defined $allocated{$allocaddr}) {
  151.                     printf ("+ %#010x Alloc %d duplicate: %s %s\n",
  152.                             hex($allocaddr), $nr, &location($addrwas{$allocaddr}),
  153.                             $where);
  154.                 } else {
  155.                     $allocated{$allocaddr}=$howmuch;
  156.                     $addrwas{$allocaddr}=$where;
  157.                 }
  158.                 last SWITCH;
  159.             }
  160.             if ($cols[$n] eq "-") {
  161.                 if (defined $allocated{$allocaddr}) {
  162.                     undef $allocated{$allocaddr};
  163.                     undef $addrwas{$allocaddr};
  164.                 } else {
  165.                     printf ("- %#010x Free %d was never alloc'd %s\n",
  166.                             hex($allocaddr), $nr, &location($where));
  167.                 }
  168.                 last SWITCH;
  169.             }
  170.             if ($cols[$n] eq "<") {
  171.                 if (defined $allocated{$allocaddr}) {
  172.                     undef $allocated{$allocaddr};
  173.                     undef $addrwas{$allocaddr};
  174.                 } else {
  175.                     printf ("- %#010x Realloc %d was never alloc'd %s\n",
  176.                             hex($allocaddr), $nr, &location($where));
  177.                 }
  178.                 last SWITCH;
  179.             }
  180.             if ($cols[$n] eq ">") {
  181.                 if (defined $allocated{$allocaddr}) {
  182.                     printf ("+ %#010x Realloc %d duplicate: %#010x %s %s\n",
  183.                             hex($allocaddr), $nr, $allocated{$allocaddr},
  184.                             &location($addrwas{$allocaddr}), &location($where));
  185.                 } else {
  186.                     $allocated{$allocaddr}=$howmuch;
  187.                     $addrwas{$allocaddr}=$where;
  188.                 }
  189.                 last SWITCH;
  190.             }
  191.             if ($cols[$n] eq "=") {
  192. # Ignore "= Start".
  193.                 last SWITCH;
  194.             }
  195.             if ($cols[$n] eq "!") {
  196. # Ignore failed realloc for now.
  197.                 last SWITCH;
  198.             }
  199.         }
  200. }
  201. close (DATA);

  202. # Now print all remaining entries.
  203. @addrs= keys %allocated;
  204. $anything=0;
  205. if ($#addrs >= 0) {
  206.     foreach $addr (sort @addrs) {
  207.         if (defined $allocated{$addr}) {
  208.             if ($anything == 0) {
  209.                 print "\nMemory not freed:\n-----------------\n";
  210.                 print ' ' x (10 - 7), "Address Size Caller\n";
  211.                 $anything=1;
  212.             }
  213.             printf ("%#010x %#8x at %s\n", hex($addr), $allocated{$addr},
  214.                     &location($addrwas{$addr}));
  215.         }
  216.     }
  217. }
  218. print "No memory leaks.\n" if ($anything == 0);

  219. exit $anything != 0;




阅读(3299) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:syslog--无法输出debug日志信息

给主人留下些什么吧!~~