一種定位內存泄露的方法(Linux)

目的:

本文是《一種定位內存泄露的方法(Solaris)》對應的Linux版本,調試器使用gdb。主要介紹實例部分。其餘請見《一種定位內存泄露的方法(Solaris)》。c++

實例:

模擬new失敗的程序:shell

#include <stdexcept>spa

class ABC指針

{調試

public:日誌

        virtual ~ABC(){}orm

        int i;內存

        int j;cmd

};it

 

void f()

{

        for (int i = 0; i < 1000; ++i)

        {

                ABC* p = new ABC;

        }

        throw std::bad_alloc();

}

 

int main()

{

        f();

        return 0;

}

1) 編譯運行此段代碼。產生一個core文件

2) gdb打開這個core文件:

gdb a.out core

(gdb) run

Starting program: /test/new_fail/a.out

terminate called after throwing an instance of 'std::bad_alloc'

  what():  std::bad_alloc

 

Program received signal SIGABRT, Aborted.

0x00007ffff733f645 in raise () from /lib64/libc.so.6

(gdb) info proc

process 10683

cmdline = '/test/new_fail/a.out'

cwd = '/test/new_fail'

exe = '/test/new_fail/a.out'

(gdb) shell pmap 10683

10683: a.out

START               SIZE     RSS     PSS   DIRTY    SWAP PERM MAPPING

0000000000400000      4K      4K      4K      0K      0K r-xp /test/new_fail/a.out

0000000000600000      4K      4K      4K      4K      0K r--p /test/new_fail/a.out

0000000000601000      4K      4K      4K      4K      0K rw-p /test/new_fail/a.out

0000000000602000    132K     32K     32K     32K      0K rw-p [heap]

(略)

Total:            11468K   1048K    684K    180K      0K

 

360K writable-private, 11108K readonly-private, 0K shared, and 1048K referenced

 

能夠看到heap空間的起始地址是0x0000000000602000,共132K字節,即132*1024=135168字節。

3) 由於是64位應用程序,因此指針佔8字節。因此須要遍歷的指針個數爲135168/8=16896

4) 將結果輸出到日誌文件gdb.txt中:

(gdb) set height 0

(gdb) set logging on

Copying output to gdb.txt.

(gdb) x/16896a 0x0000000000602000

gdb.txt的內容:

0x602000:       0x0     0x21

0x602010:       0x400b30 <_ZTV3ABC+16>  0x0

0x602020:       0x0     0x21

0x602030:       0x400b30 <_ZTV3ABC+16>  0x0

….

5) 過濾gdb.txt

awk '{print $2"/n"$3}' gdb.txt|c++filt|grep vtable>gdb_vtable.txt

gdb_vtable.txt的內容爲:

<vtable for ABC+16>

<vtable for ABC+16>

<vtable for ABC+16>

<vtable for ABC+16>

….

6) gdb_vtable.txt的內容導入到SQLServer中(若是記錄很少,能夠用Excel代替)。表名爲gdb_vtable,第一列Col001爲符號。對其分組求和:

select Col001, count(1) quantity from gdb_vtable

group by Col001

order by quantity desc

結果爲:

Col001                                                                                    quantity

<vtable for ABC+16>                                                              1000

<vtable for std::bad_alloc@@GLIBCXX_3.4+16>                1

可知core裏有1000ABC,遍歷使用ABC的代碼,可知存在泄漏。

相關文章
相關標籤/搜索