Monday, September 23, 2013

MEMWATCH: A Memory Debugging Tool


We can say that C language is one of the most standard programming language on Linux systems as this language provides a great deal of control over dynamic memory allocation. So C language provides a lot of freedom to control your program as you wish. But this can cause memory management problems and also this can degrade our program. We use malloc() function to allocate memory but forget to released that memory with corresponding free() call which can cause Memory leaks which is one of the memory management problem. Buffer overruns i.e. writing on the previous memory locations that has already been allocated for an array can also be the problem. These problems are difficult to detect.

So there is as memory debugging tool known as MEMWATCH which is an open source memory error detection tool for C. MEMWATCH is a user level memory debugging tool. This tool has been written by Johan Lindh. You can download MEMWATCH from here.

Now how to use it? When you write the C code just simply add the header file to your code and by defining it in the gcc statement , we can track the memory leaks in our program. It will provides a log of results and detects the unfreed memory, overflow, underflow etc.

Here is program sample memory.c :

#include <stdlib.h>
#include <stdio.h>
#include "memwatch.h"

int main()
{
  char *ptr1;
  char *ptr2;

  ptr1 = malloc(320);
  ptr2 = malloc(320);

  ptr2 = ptr1;
  free(ptr2);
  free(ptr1);
}
In above code, we can see that first 320 byte blocks of memory is allocated then the pointer to the first block is set to the second block, so the address of the second block is lost which cause memory leaks.

Now compile the code:
 
  gcc -DMEMWATCH -DMW_STDIO memory.c memwatch c -o memory

After that when we run the program, MEMWATCH reproduces a report of leaked memory.

     ./memory


 You can also see the memwatch.log file.