开发者

Using mtrace for c++

When i use mtr开发者_如何学Pythonace in my c++ programme,i get output like the following

Memory not freed:

  Address           Size        Caller 
 0x0804a3c8         0x4 at     0x400b159f 

How do i know where in the code is 0x400b159f?


On many unix systems you can also use the addr2line utility to map an address back to a file name and line number. This utility requires that the code be compiled with the debug flag (-g for gcc). For a program named wombat you would use it like such:

addr2line -e wombat 0x400b159f

and it will print out something like

wombat_helper.c:1023

if you get ??:0 it can't find the function.

UPDATE: The memory addresses reported by mtrace are the locations where the malloc and free functions are called. For C++, this is almost always in the new and delete operators, and thus would be of very limited use, without other information, such as a stack trace to tell where in your program new or delete operator is called from.


You can load your program in gdb and use info symbol command

[root@localhost ~]#
[root@localhost ~]# mtrace ./a.out mtrace.log

Memory not freed:
-----------------
   Address     Size     Caller
0x08de3378      0x4  at 0x42028da
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]# gdb ./a.out
GNU gdb (GDB) 7.2
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /root/a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x80484fd: file test.cpp, line 6.

Temporary breakpoint 1, main () at test.cpp:6
6               mtrace();
(gdb) info symbol 0x42028da
operator new(unsigned int) + 42 in section .text of /usr/lib/libstdc++.so.6
(gdb)

Also you may need to start your program until the beginning of the main procedure to load all symbols from shared libraries. In the example above the caller is operator new which is located in libstdc++.so.6.


You need to insert mtrace hooks into your program.

#include <mcheck.h>

Then call

mtrace();

Before you start allocating any memory.

Also compile with -g if using g++.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜