Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Memory Leak detection Program without using any tools (http://www.go4expert.com/articles/memory-leak-detection-program-using-t9133/)

asadullah.ansari 4Mar2008 21:07

Memory Leak detection Program without using any tools
 
I worked for a long time for this article. This program is tested on Sun-Solaris system using gcc compiler.

In market, there are a lot of tools for detecting the memory leaks. Here I made a program which has to include in your source file and it will tell the desired informations to find where memory leaks happen.

There are two files one is findLeak.c and other is findLeak.h . Source file is test.c , this is your program which you want to check memory leaks.

Concept is that when user call library function "malloc or calloc " for allocating dynamic memory, then we have to call our malloc or calloc (In case of my source code 'MyCalloc' function in place of 'calloc' and MyMalloc function in place of 'malloc'). So we have to define malloc to your malloc and in .c file you have to undef malloc and calloc By this way we can call our MyMalloc or MyCalloc function and in this function we will call another function which keeps all info about how much memory allocated. We will do the same for Library function "free" to deallocating memory( In my source file "MyFree" is used in plae of free function).

Now for keeping information, i made a simple singly linked list. which will add info about memory when user call "malloc" or "calloc" function and will also keep information when user call "free" function.

By program you can easily understand.

Heder File : findLeak.h

Code: c

#define   uint                 unsigned int
#define   cchar                const char                     
#define   OutFile             "/home/asadulla/test/MemLeakInfo.txt"   // Just Suppose
#define  MAX_FILENAME_LENGTH   256
#define  calloc(objs, nSize)          MyCalloc (objs, nSize, __FILE__, __LINE__)
#define  malloc(nSize)                MyMalloc (nSize, __FILE__, __LINE__)
#define  free(rMem)                   MyFree(rMem)

// This structure is keeping info about memory leak

struct InfoMem
{
      //starting address of memory where pointer points
    void *addr;
      //Total size of memory in bytes which By malloc
      //allocates  memory dynamically */
    uint nSize;
      //Source File Name which you want
      //to  find memory leak information
    char fileName[MAX_FILENAME_LENGTH];
        //Line number of source File due to                                                                             
       // which User forget to deallocate   memory
    uint lineNumber;
};
typedef struct InfoMem infoMem;

//This is link list of InfoMem which keeps a List of memory Leak in a source file

struct LeakMem
{
    infoMem memData;     
    struct LeakMem *nxt;   // Next Memory leak Block
};
typedef struct LeakMem leakMem;

// This function is used for writing into file to see the memory leaks summary
void WriteMemLeak(void);

// These two function add information of memory leak information when user
// calls malloc or calloc
void SubAddMemInfo(void *rMem, uint nSize,  cchar  *file, uint lno);
void SubAdd(infoMem alloc_info);

// These two function remove and deallocated  memory and remove the leak
//  information when user calls free function
void ResetInfo(uint pos); //erase
void DeleteAll(void); //clear(void);

// This is hidden to user , This function will call when user call malloc function
void *MyMalloc(uint size, cchar *file, uint line);
// This is hidden to user , This function will call when user call calloc function
void *MyCalloc(uint elements, uint size, cchar * file, uint lno);
// This is hidden to user , This function will call when user call free function
void  MyFree(void * mem_ref);


Source File: findLeak.c

Code: c

#include    <stdio.h>
#include    <malloc.h>
#include    <string.h>
#include    "findLeak.h"

#undef    malloc
#undef    calloc
#undef   free


static leakMem * ptr_start = NULL;
static leakMem * ptr_next =  NULL;




// -----------------------------------------------------------
// Name: MyMalloc
// Desc: This is hidden to user. when user call malloc function then
//       this function will be called.


void *MyMalloc (uint nSize, cchar* file, uint lineNumber)
{
    void * ptr = malloc (nSize);
    if (ptr != NULL)
    {
        SubAddMemInfo(ptr, nSize, file, lineNumber);
    }
    return ptr;
}

// -----------------------------------------------------------
// Name: MyCalloc
// Desc: This is hidden to user. when user call calloc function then
//       this function will be called.


void * MyCalloc (uint elements, uint nSize, const char * file, uint lineNumber)
{
    uint tSize;
    void * ptr = calloc(elements , nSize);
    if(ptr != NULL)
    {
        tSize = elements * nSize;
        SubAddMemInfo (ptr, tSize, file, lineNumber);
    }
    return ptr;
}

// -----------------------------------------------------------
// Name: SubAdd
// Desc: It's actually  Adding the Info.


void SubAdd(infoMem alloc_info)
{
    leakMem * mem_leak_info = NULL;
    mem_leak_info = (leakMem *) malloc (sizeof(leakMem));
    mem_leak_info->memData.addr = alloc_info.addr;
    mem_leak_info->memData.nSize = alloc_info.nSize;
    strcpy(mem_leak_info->memData.fileName, alloc_info.fileName);
    mem_leak_info->memData.lineNumber = alloc_info.lineNumber;
    mem_leak_info->nxt = NULL;

    if (ptr_start == NULL) 
    {
        ptr_start = mem_leak_info;
        ptr_next = ptr_start;
    }
    else {
        ptr_next->nxt = mem_leak_info;
        ptr_next = ptr_next->nxt;            
    }

}



// -----------------------------------------------------------
// Name: ResetInfo
// Desc: It erasing the memory using by List on the basis of info( pos)


void ResetInfo(uint pos)
{

    uint index = 0;
    leakMem * alloc_info, * temp;
   
    if(pos == 0)
    {
        leakMem * temp = ptr_start;
        ptr_start = ptr_start->nxt;
        free(temp);
    }
    else
    {
        for(index = 0, alloc_info = ptr_start; index < pos;
            alloc_info = alloc_info->nxt, ++index)
        {
            if(pos == index + 1)
            {
                temp = alloc_info->nxt;
                alloc_info->nxt =  temp->nxt;
                free(temp);
                break;
            }
        }
    }
}

// -----------------------------------------------------------
// Name: DeleteAll
// Desc: It deletes the all elements which resides on List

void DeleteAll()
{
    leakMem * temp = ptr_start;
    leakMem * alloc_info = ptr_start;

    while(alloc_info != NULL)
    {
        alloc_info = alloc_info->nxt;
        free(temp);
        temp = alloc_info;
    }
}


// -----------------------------------------------------------
// Name: MyFree
// Desc:


void MyFree(void * mem_ref)
{
        uint loop;
   // if the allocated memory info is part of the list, removes it
    leakMem  *leak_info = ptr_start;
    /* check if allocate memory is in our list */
    for(loop = 0; leak_info != NULL; ++loop, leak_info = leak_info->nxt)
    {
        if ( leak_info->memData.addr == mem_ref )
        {
            ResetInfo(loop);
            break;
        }
    }
    free(mem_ref);
}


// -----------------------------------------------------------
// Name: SubAddMemInfo
// Desc: it also fill the the Info


void SubAddMemInfo (void * mem_ref, uint nSize, cchar * file, uint lineNumber)
{
    infoMem AllocInfo;

    /* fill up the structure with all info */
    memset( &AllocInfo, 0, sizeof ( AllocInfo ) );
    AllocInfo.addr  = mem_ref;
    AllocInfo.nSize = nSize;
    strncpy(AllocInfo.fileName, file, MAX_FILENAME_LENGTH);
    AllocInfo.lineNumber = lineNumber;
   
    /* SubAdd the above info to a list */
    SubAdd(AllocInfo);
}

// -----------------------------------------------------------
// Name: WriteMemLeak
// Desc: It writes information about Memory leaks in a file
//       Example: File is as : "/home/asadulla/test/MemLeakInfo.txt"



void WriteMemLeak(void)
{
    uint index;
    leakMem *leak_info;

    FILE * fp_write = fopen(OutFile, "wt");
    char info[1024];

    if(fp_write != NULL)
    {
        sprintf(info, "%s\n", "SUMMARY ABOUT MEMORY LEAKS OF YOUR SOURCE FILE ");
        fwrite(info, (strlen(info) + 1) , 1, fp_write);
        sprintf(info, "%s\n", "-----------------------------------");   
        fwrite(info, (strlen(info) + 1) , 1, fp_write);
       
        for(leak_info = ptr_start; leak_info != NULL; leak_info = leak_info->nxt)
        {

            sprintf(info, "Name of your Source File                 : %s\n", leak_info->memData.fileName);
            fwrite(info, (strlen(info) + 1) , 1, fp_write);

            sprintf(info, "Starting Address                         : %d\n", leak_info->memData.addr);
            fwrite(info, (strlen(info) + 1) , 1, fp_write);

            sprintf(info, " Total size Of memory Leak               : %d bytes\n", leak_info->memData.nSize);         
            fwrite(info, (strlen(info) + 1) , 1, fp_write);

            sprintf(info, "Line Number for which no DeAllocation    : %d\n", leak_info->memData.lineNumber);
            fwrite(info, (strlen(info) + 1) , 1, fp_write);

            sprintf(info, "%s\n", "-----------------------------------");   
            fwrite(info, (strlen(info) + 1) , 1, fp_write);
      fwrite(info, (strlen(info) + 1) , 1, fp_write);
        }
    }   
    DeleteAll();
}

These two files (header file and source file) user has to include in his source file to which user want to find memory leak.

Source File for detecting memory leak is as Here you can gice your own source file and in this source file you have write onle line to include file #include"findLeak.h"


Source File : test.c

Code: c

#include<malloc.h>
#include"findLeak.h"

int main()
{
    int *p1 = (int *)malloc(10)
    int *p2 = (int *)calloc(10, sizeof(int));
    char *p3 = (char *) calloc(15, sizeof(float));
    float *p4 = (float*) malloc(16);
    free(p2);
    WriteMemLeak();
    return 0;
 }



Now user can compile these programmes in a console as :
> g++ test.c findLeak.c
and give a command for run
> ./a.out

then go to you your directory where you have defined a macro "OutFile" and open this defined file and you can see the results.

Output of above source file is as:

Code: output

SUMMARY ABOUT MEMORY LEAKS OF YOUR SOURCE FILE
-----------------------------------
Name of your Source File                 : test.c
Starting Address                         : 184960
 Total size Of memory Leak               : 10 bytes
Line Number for which no DeAllocation    : 7
-----------------------------------
-----------------------------------
Name of your Source File                 : test.c
Starting Address                         : 187104
 Total size Of memory Leak               : 60 bytes
Line Number for which no DeAllocation    : 9
-----------------------------------
-----------------------------------
Name of your Source File                 : test.c
Starting Address                         : 184984
 Total size Of memory Leak               : 16 bytes
Line Number for which no DeAllocation    : 10
-----------------------------------
-----------------------------------

Now you can try to make you own source file just like test.c.

asadullah.ansari 5Mar2008 10:02

Re: Memory Leak detection Program without using any tools
 
Really i hard work for it. I request to all, Just read it then you can have basic idea of PURIFY.

debleena_doll2002 5Mar2008 10:13

Re: Memory Leak detection Program without using any tools
 
Strange!!! Really nice way to detect memory leak in an application.

ron_genum 5Mar2008 14:22

Re: Memory Leak detection Program without using any tools
 
just wana ask what type og programing language should i use for that sample program?

asadullah.ansari 5Mar2008 14:53

Re: Memory Leak detection Program without using any tools
 
u can use "C or C++"

ron_genum 5Mar2008 15:02

Re: Memory Leak detection Program without using any tools
 
great i got some idea bout using c++ but what i wanna know also is what does this memory leak is? does it have something to do would system errors? or slow file retrieval?

asadullah.ansari 5Mar2008 15:28

Re: Memory Leak detection Program without using any tools
 
you can read detail from somewhere about memory leak...

Memory leak occurs in your program when you are allocating memory dynamically(this memory is allocated on heap by operating system when you are calling malloc or calloc in C) and you forget to deallocate that memory. Now this memory will be called as "memory leak" .
Example:

int main()
{
int *p1 = (int *)malloc(10);
}
If your program will go out of scope of integer pointer p1 then memory allocated by pointer p1 will be leak. because you did'nt call free(p1) function.

debleena_doll2002 5Mar2008 15:37

Re: Memory Leak detection Program without using any tools
 
Quote:

Originally Posted by ron_genum
great i got some idea bout using c++ but what i wanna know also is what does this memory leak is? does it have something to do would system errors? or slow file retrieval?

You can search on google. Memory leaks related things you can get anywhere. You are asking very basic question.

aisha.ansari84 5Mar2008 17:00

Re: Memory Leak detection Program without using any tools
 
can you please give me some more details about memory leak

aisha.ansari84 5Mar2008 17:02

Re: Memory Leak detection Program without using any tools
 
suppose there is a function which allocates memory for a temporary variable temp , does some work and then returns temp.

i think there should be a memory leak in this case as i cannot free temp ,right so how can i control memory leak here

asadullah.ansari 5Mar2008 17:20

Re: Memory Leak detection Program without using any tools
 
Quote:

Originally Posted by aisha.ansari84
suppose there is a function which allocates memory for a temporary variable temp , does some work and then returns temp.

i think there should be a memory leak in this case as i cannot free temp ,right so how can i control memory leak here

I think this example will solved your problem.
Code:

#include<malloc.h>

int* fun();
int main()
{
  int *p2 = fun();
  free(p2);
  return 0;
 }

int* fun()
{
  int *p1 = (int *)malloc(10);
  return p1;
}


asadullah.ansari 5Mar2008 17:36

Re: Memory Leak detection Program without using any tools
 
to check memory leak, you can use my program as
Code:

#include<malloc.h>
#include "findLeak.h"


int* fun();
int main()
{
  int *p2 = fun();
  free(p2);
  WriteMemLeak();
  return 0;
 }

int* fun()
{
  int *p1 = (int *)malloc(10);
  return p1;

}


aisha.ansari84 5Mar2008 17:59

Re: Memory Leak detection Program without using any tools
 
that means you want to say that i need to free the memory in the function where i m receiving the value returned by temporary variable.

aisha.ansari84 5Mar2008 18:01

Re: Memory Leak detection Program without using any tools
 
understood and clear

alramesh 5Mar2008 20:06

Re: Memory Leak detection Program without using any tools
 
I run this program for my application. It's working. Too Cooooooooool.
Thanks asadullah.ansari

flyingfor 5Mar2008 20:19

Re: Memory Leak detection Program without using any tools
 
Excellent asadullah.ansari. I cannt imagine. I am very happy to see this memory leak detector program so simple and understandable.

flyingfor 6Mar2008 09:55

Re: Memory Leak detection Program without using any tools
 
Can you tell me in different languages how to use this program?

ron_genum 6Mar2008 09:57

Re: Memory Leak detection Program without using any tools
 
suppose ive detected memory leaks on my OS as I run that program, what will I do next?
Is there any posible ways to prevent it or get rid of it?

asadullah.ansari 6Mar2008 09:59

Re: Memory Leak detection Program without using any tools
 
Quote:

Originally Posted by flyingfor
Can you tell me in different languages how to use this program?

You can make my program in binary also.

Beauty of this program is that only one interface you have to use, that is "WriteMemLeak()" only.
If any way other languages support to use C Interface, then you can use it.

asadullah.ansari 6Mar2008 11:07

Re: Memory Leak detection Program without using any tools
 
Quote:

Originally Posted by ron_genum
suppose ive detected memory leaks on my OS as I run that program, what will I do next?
Is there any posible ways to prevent it or get rid of it?

I am not getting your question.

Is it true what i am understanding that "memory leak is in OS not in your program".
If it is true then your question is
"How to detect memory leak coming in OS by program posted by asadullah.ansari? "

Response me?

rahul.mca2001 6Mar2008 12:54

Re: Memory Leak detection Program without using any tools
 
i tried and it really works well

bashamsc 7Mar2008 15:48

Re: Memory Leak detection Program without using any tools
 
Nice program to detect memory leak. But i want to know how to recover the memory after memory leak and how to prevent it.

asadullah.ansari 7Mar2008 19:48

Re: Memory Leak detection Program without using any tools
 
This program will tell you
1. line number
2. source file name
3. starting address
4. total bytes .
If this is your program then go to that line and call free function for that pointer which is pointing to memory and not deallocated.

If that is not your program means it may be in binary then You have four information by running this program , then take a pointer which will point to constant address as above 3.
and set the offset as required based on as above 4 info. then call free function for this pointer.

shabbir 9Mar2008 10:58

Re: Memory Leak detection Program without using any tools
 
bubyfound, Make sure we discuss only in English.

debleena_doll2002 10Mar2008 11:06

Re: Memory Leak detection Program without using any tools
 
Quote:

Originally Posted by shabbir
bubyfound, Make sure we discuss only in English.

I am unable to get yout statement. shabbir, Please Can you use QUOTE so that we can easily identify.

shabbir 10Mar2008 11:48

Re: Memory Leak detection Program without using any tools
 
bubyfound, had one post in non-English and so its directed to him. I have not quoted his non-english posts

rashida.par 10Mar2008 11:48

Re: Memory Leak detection Program without using any tools
 
very nice article

donakalz 21Mar2008 23:06

Re: Memory Leak detection Program without using any tools
 
Thanks man for the very very nice code.

However, I am trying to create a version which works for C++ operators new and delete like this:

#define new (elemSize) MyNew (elemSize, __FILE__, __LINE__)
#define new [](elemSize) MyNewArray (elemSize, __FILE__, __LINE__)
#define delete(memPointer) MyDelete (memPointer)
#define delete [](memPointer) MyDeleteArray (memPointer)

and I get the following compiler errors:
24:1 [Warning] "new" redefined
26:1 [Warning] "delete" redefined


Can you think of a workaround for this? Thanks.

Don

donakalz 24Mar2008 16:54

Re: Memory Leak detection Program without using any tools
 
Wow. So quiet in here. Hello? Anybody here?

lead.smart34 25Mar2008 15:17

Re: Memory Leak detection Program without using any tools
 
really a very nice code

sareen 25Mar2008 15:39

Re: Memory Leak detection Program without using any tools
 
nice

sareen 25Mar2008 15:44

Re: Memory Leak detection Program without using any tools
 
sir very easy program

asadullah.ansari 26Mar2008 14:55

Re: Memory Leak detection Program without using any tools
 
Quote:

Originally Posted by donakalz
Thanks man for the very very nice code.

However, I am trying to create a version which works for C++ operators new and delete like this:

#define new (elemSize) MyNew (elemSize, __FILE__, __LINE__)
#define new [](elemSize) MyNewArray (elemSize, __FILE__, __LINE__)
#define delete(memPointer) MyDelete (memPointer)
#define delete [](memPointer) MyDeleteArray (memPointer)

and I get the following compiler errors:
24:1 [Warning] "new" redefined
26:1 [Warning] "delete" redefined


Can you think of a workaround for this? Thanks.

Don

How it will happen? Are You sure about this warning? Because I am using Flexlint tools for making zero warning also.
By any way can you give at which plateform and compiler you are using ?

donakalz 27Mar2008 04:11

Re: Memory Leak detection Program without using any tools
 
I use windows xp and a DevC++ compiler. I get the error that new and delete are redefined. I also get the error with Netbeans 6.1 for C++. Maybe you could post some code of yours to show how you accomplished this task. Thanks.

don

asadullah.ansari 28Mar2008 10:40

Re: Memory Leak detection Program without using any tools
 
Quote:

Originally Posted by donakalz
I use windows xp and a DevC++ compiler. I get the error that new and delete are redefined. I also get the error with Netbeans 6.1 for C++. Maybe you could post some code of yours to show how you accomplished this task. Thanks.

don

I dont know how you are using. Have you some sense. Any compiler is not mad like you. How it will give redefined. I have define as macro. Do you have some skill. If you have some little bit skill then it will run.

shabbir 4Apr2008 18:45

Re: Memory Leak detection Program without using any tools
 
Nomination for article of the month of March

shabbir 17Apr2008 15:51

Re: Memory Leak detection Program without using any tools
 
Vote here - Voting for article of the month for Mar 2008

shabbir 30Apr2008 12:00

Re: Memory Leak detection Program without using any tools
 
Winner of article of the month for Mar 2008

saroj.pandarkl 21Jun2008 16:16

Re: Memory Leak detection Program without using any tools
 
Hi
Aa I saw through this forum many people are asking basic question what is memory leak and they are advised to go through google.Can any do a little favour like when creating any variable or ointer things in which area of memory it stores(i mean to say like code segment ,data seg etc).Explanation (undestanding)required on it before going about memory leak

inkuar.ikkr 24Jun2008 22:31

Re: Memory Leak detection Program without using any tools
 
Hello asadullah,

Could you please send the findleak program for C++ for New, Delete .. methods?

Thanks,
INDRA


All times are GMT +5.5. The time now is 19:47.