MEMWATCH
MEMWATCH is a fault tolerant (can repair its own data structures) memory leak and corruption detection tool. You add a header file to your souce code files, and compile with MEMWATCH defined or not. MEMWATCH can detect double-frees and erroneous frees, unfreed memory, overflow and underflow to memory buffers, and wild pointer writes. It collects allocation statistics on the application, module, or line level.
MEMWATCH can also be used to analyze a program’s memory usage from its provided logging facilities. Memwatch differs from most debugging software because it is compiled directly into the program which will be debugged, instead of being compiled separately and loaded into the program at runtime.
Using memwatch
MEMWATCH, written by Johan Lindh.
MEMWATCH is an open source memory error detection tool for C that you can download it from here.
You can use it by simply adding a header file to your code and defining MEMWATCH in your gcc statement, you can track memory leaks and corruptions in your program.
code of test1.c
#include "stdlib.h"
#include " stdio.h"
#include "memwatch.h"
int main(void)
{
int *ptr1,*ptr2; ptr1 = malloc(1024);
ptr2 = malloc(1024);
ptr2 = ptr1; free(ptr2); free(ptr1);
}
The code in test1.c allocates two 1024-byte blocks of memory, and then the pointer to the first block is set to the second block. As a result, the address of the second block is lost, and there is a memory leak.
Now compile memwatch.c with test1. The following is an example makefile:
Make file
gcc -DMEMWATCH -DMW_STDIO test1.c memwatch.c -o test1
When you run the test1 program, it produces a report of leaked memory. Listing 2 shows the example memwatch.log output file.
| output: test1 memwatch.log file |
|---|
| MEMWATCH 2.71 Copyright (C) 1992-1999 Johan Lindh Started at Mon Aug 4 17:48:11 2008 Modes: __STDC__ 32-bit mwDWORD==(unsigned long) mwROUNDALLOC==4 sizeof(mwData)==32 mwDataSize==32 double-free: <4> test1.c(16), 0x8051374 was freed from test1.c(15) Stopped at Mon Aug 4 17:48:11 2008 unfreed: <2> test1.c(12), 1024 bytes at 0x80517a4 {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 : 2048 T)otal of all alloc() calls : 2048 U)nfreed bytes totals : 1024 |
MEMWATCH gives you the exact line that has the problem.
It tells you If you free an already freed pointer or about unfreed memory. The section at the end of the log displays statistics, including how much memory was leaked, how much was used, and the total amount allocated.
Comments
Leave a Reply