如何用dmalloc檢測記憶體洩漏(原創)
1.從www.dmalloc.com下載一個rpm包(你也可以下載原始碼包,本人比較懶 :) )
2.安裝
3.export DMALLOC_OPTIONS=log=logname,debug=0x3
注:logname是你要生成記錄的檔名
4.在你需要檢測的原始碼裡包含dmalloc.h
#include <dmalloc.h>
5.儲存退出編譯
gcc -ldmalloc -o program code.c
6../program
會在當前目錄下生成一個logname,現在你就可以看到你的程式未釋放的記憶體了
以下是我一個程式的生成的log:
1134286917: 23: Dmalloc version '5.4.2' from 'http://dmalloc.com/'
1134286917: 23: flags = 0x3, logfile 'logfile'
1134286917: 23: interval = 0, addr = 0, seen # = 0, limit = 0
1134286917: 23: starting time = 1134286917
1134286917: 23: process pid = 12088
1134286917: 23: WARNING: tried to free(0) from 'module.c:23'
1134286917: 27: WARNING: tried to free(0) from 'module.c:23'
1134286917: 27: Dumping Chunk Statistics:
1134286917: 27: basic-block 4096 bytes, alignment 8 bytes
1134286917: 27: heap address range: 0x111000 to 0x49c000, 3715072 bytes
1134286917: 27: user blocks: 4 blocks, 16048 bytes (39%)
1134286917: 27: admin blocks: 6 blocks, 24576 bytes (60%)
1134286917: 27: total blocks: 10 blocks, 40960 bytes
1134286917: 27: heap checked 0
1134286917: 27: alloc calls: malloc 14, calloc 0, realloc 0, free 13
1134286917: 27: alloc calls: recalloc 0, memalign 0, valloc 0
1134286917: 27: alloc calls: new 0, delete 0
1134286917: 27: current memory in use: 432 bytes (3 pnts)
1134286917: 27: total memory allocated: 6204 bytes (14 pnts)
1134286917: 27: max in use at one time: 4988 bytes (12 pnts)
1134286917: 27: max alloced with 1 call: 4124 bytes
1134286917: 27: max unused memory space: 4740 bytes (48%)
1134286917: 27: top 10 allocations:
1134286917: 27: total-size count in-use-size count source
1134286917: 27: 4124 1 0 0 ra=0x6e5910
1134286917: 27: 864 6 0 0 module.c:43
1134286917: 27: 432 3 0 0 module.c:133
1134286917: 27: 432 3 432 3 module.c:185
1134286917: 27: 352 1 0 0 ra=0x6b276d
1134286917: 27: 6204 14 432 3 Total of 5
1134286917: 27: Dumping Not-Freed Pointers Changed Since Start:
1134286917: 27: not freed: '0x111400|s1' (144 bytes) from 'module.c:185'
1134286917: 27: not freed: '0x111500|s1' (144 bytes) from 'module.c:185'
1134286917: 27: not freed: '0x111600|s1' (144 bytes) from 'module.c:185'
1134286917: 27: total-size count source
1134286917: 27: 432 3 module.c:185
1134286917: 27: 432 3 Total of 1
1134286917: 27: ending time = 1134286917, elapsed since start = 0:00:00
可以看到,在185行的程式碼分配的432個位元組的記憶體未被釋放,...............................over