分类: C/C++
2011-04-12 13:01:27
下面是一个memwatch使用的例子:
1.
# cat test.c
#include
#include
#include "memwatch.h"
int main(void)
{
char *ptr1;
char *ptr2;
ptr1 = malloc(512);
ptr2 = malloc(512);
ptr2 = ptr1;
free(ptr2);
free(ptr1);
}
2.
# cat Makefile
test:
gcc -DMEMWATCH -DMEMWATCH_STDIO test.c memwatch.c -o test
3.
make 之后执行 ./test
# ./test
MEMWATCH detected 2 anomalies
查看 log内容:
4.
# cat memwatch.log
============= MEMWATCH 2.71 Copyright (C) 1992-1999 Johan Lindh =============
Started at Thu Feb 24 10:13:41 2011
Modes: __STDC__ 64-bit mwDWORD==(unsigned long)
mwROUNDALLOC==8 sizeof(mwData)==32 mwDataSize==32
double-free: <4> test.c(23), 0x8e444c8 was freed from test.c(22)
Stopped at Thu Feb 24 10:13:41 2011
unfreed: <2> test.c(20), 512 bytes at 0x8e44700 {FE FE FE FE FE FE FE FE FE FE FE FE FE FE FE FE ................}
Memory usage statistics (global):
N)umber of allocations made: 2
L)argest memory usage : 1024
T)otal of all alloc() calls: 1024
U)nfreed bytes totals : 512
可以看出:
double-free: <4> test.c(23), 0x8e444c8 was freed from test.c(22):test.c的第23行内存双重释放。该内存在22行已被释放过。
unfreed: <2> test.c(20), 512 bytes at 0x8e44700 : test.c的第20行分配的内存没被释放。
最后是一个统计结果:
动态分配了两次内存。一共分配了1024,未释放512.