dmalloc arm-linux平臺使用
話說“工欲善其事,必先得其器”,用C語言寫程序,最怕遇到個什么內存泄漏,內存越界訪問了,心里那個急啊。。。
如果在i368-linlux上,valgrind工具是首選,但在arm-linux平臺上,如何呢,dmalloc就是一個不錯的選擇。當然,IBM的purify是另外一個級別的選手,不提也罷。
1. 到官方網站下載dmalloc: www.dmalloc.com
2. 交叉編譯dmalloc
2.1 configure
因為configure過程中要在PC上執行test程序,而交叉編譯的test程序在PC上無法運行,導致configure通不過,因此,我沒有加上--host=arm-linux選項
./configure --prefix=/opt/crosstool/arm-linux/gcc-3.4.4-glibc-2.3.5/arm-linux/arm-linux/ --enable-cxx --enable-threads
其中opt/crosstool/arm-linux/gcc-3.4.4-glibc-2.3.5/arm-linux/arm-linux/是我的交叉編譯環境的目錄
2.2
修改環境變量,偷梁換柱
export PATH=/opt/crosstool/arm-linux/gcc-3.4.4-glibc-2.3.5/arm-linux/arm-linux/bin/:$PATH
其中交叉編譯工具在/opt/crosstool/arm-linux/gcc-3.4.4-glibc-2.3.5/arm-linux/arm-linux/bin/下,且名字為gcc, g++等。
這時,用which gcc命令看到的將是交叉編譯工具gcc
2.3
make threadscxx
make install
這樣,就編譯出了支持線程和c++的dmalloc版本。
3. 環境配置
將交叉編譯后的dmalloc放入嵌入式板子上,執行./dmalloc -b -l logfile -i 100 low
會看到有兩行輸出:
DMALLOC_OPTIONS=debug=0x4e48503,inter=100,log=logfile
export DMALLOC_OPTIONS
把這兩行作為shell腳本執行一下,即是設置環境變量
4. 寫代碼測試dmalloc啦
簡單的程序:
#include <signal.h>
#include <unistd.h>
#include <cstdlib>
int main()
{
char *p = (char *)malloc(10);
for(int i = 0; i < 11; ++i)
p[i] = 'a';
return 0;
}
上面的程序有明顯的內存越界訪問。
用如下命令編譯之:
$ arm-linux-g++ try.cpp -DDMALLOC_FUNC_CHECK -ldmalloc
生成a.out
在板子上執行./a.out
會有logfile產生,內容如下:
948436802: 1: Dmalloc version '5.5.2' from 'http://dmalloc.com/'
948436802: 1: flags = 0x4e48503, logfile 'logfile'
948436802: 1: interval = 100, addr = 0, seen # = 0, limit = 0
948436802: 1: starting time = 948436802
948436802: 1: process pid = 5091
948436802: 1: error details: checking user pointer
948436802: 1: pointer '0x40016fe8' from 'unknown' prev access 'try.cpp:11'
948436802: 1: dump of proper fence-top bytes: 'i\336\312\372'
948436802: 1: dump of '0x40016fe8'-6: '\300\300\033\253\300\300aaaaaaaaaaa\336\312\372'
948436802: 1: next pointer '0x40017000' (size 0) may have run under from 'unknown'
948436802: 1: ERROR: _dmalloc_chunk_heap_check: failed OVER picket-fence magic-number check (err 27)
哈哈,OK
從上面的輸出可以看到,在訪問try.cpp 第11行分配的內存時,出現了越界訪問。
5. dmalloc也支持c++,但不完善,打印不出出錯的行號
用c++時,要用-ldmallocthcxx選項,不能用-ldmalloc
其實沒行號也沒關系,用gdb工具及打印出的地址也是可以知道行號的。
RFID管理系統集成商 RFID中間件 條碼系統中間層 物聯網軟件集成