Click here to Skip to main content
Click here to Skip to main content

Memory Leak Detection in C

By , 27 Jun 2007
 

Introduction

Memory leak has always been a part of bugs in C code where a programmer allocates memory in run time (in heap) and fails to deallocate it. And most programmers use some third party software to detect memory leak in their code.

But we can write very simple code to detect memory leak in our program.

Usually we allocate memory in C using malloc() and calloc() in run time and deallocate the reserved memory using free(). Sometimes we don't free the reserved memory which causes memory leak.

The below method is a very simple one and helps to detect memory leak in your program.

Using the Code

Let's assume you have allocated some memory in your code using malloc() and calloc() and haven't deallocated it and your code looks like below.

test.c

#include<malloc.h>
int main() 
{
    char * ptr1 = (char *) malloc (10); // allocating 10 bytes
    int * ptr2 = (int *) calloc (10, sizeof(int)); 	// allocating 40 bytes 
						// let sizeof int =  4 bytes)
    float * ptr3 = (float *) calloc (15, sizeof(float)); // allocating 60 bytes
    ............
    ............
    ............
    free(ptr2);
    return 0;
}
    
</malloc.h>

Steps to Detect Memory Leak

(I have tested the code in a Linux machine using GCC. You can test the same code in Windows as well.)

Step 1

Now to test memory leak, just add the leak_detector_c.h file to the test file and add one line to the start of main function.

Now the test code should look like below:

test.c

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

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

    atexit(report_mem_leak);

    ptr1 = (char *) malloc (10); // allocating 10 bytes        
    ptr2 = (int *) calloc (10, sizeof(int)); 	// allocating 40 bytes 
					// let sizeof int =  4 bytes)
    ptr3 = (float *) calloc (15, sizeof(float)); // allocating 60 bytes
    ............
    ............
    ............
    free(ptr2);
    return 0;
}
    
</malloc.h>

Step 2

Now compile the code and run the program:

# gcc -c leak_detector_.c
# gcc -c test.c
# gcc -o memtest leak_detctor_c.o test.o
# ./memtest
# cat /home/leak_info.txt    

Now you will get output as shown below:

Memory Leak Summary
-----------------------------------
address : 140668936
size    : 10 bytes
file    : test.c
line    : 5
-----------------------------------
address : 140669560
size    : 60 bytes
file    : test.c
line    : 7
-----------------------------------

The output shows the file name and line number which causes the memory leak and now you can free the unallocated memory. If you have multiple source files, you can add the header file in all the files where you want to detect possible memory leak and compile the program as above.

Now let's have a look into the code and see how it works.

The leak_detctor_c.h file contains some macros and the preprocessor replaces the call of malloc, calloc and free functions with xmalloc, xcalloc and xfree respectively .

While calling malloc(), our xmalloc() is called and we keep all information of the allocated memory (like the address, size, file name and line number) in a linked list. While the code calls the free() function, it actually calls our xfree() and we manage to do the cleanup task (remove the entry of the allocated memory from the list and free up the allocated memory).

At the end of the program, we can get the unallocated memory references from the list.

The line "atexit(report_mem_leak)" registers the report_mem_leak() function to be called at the end of the program and this function writes the memory leak summary into the leak_info.txt file. You can also use #pragma exit directive instead of atexit().

History

  • 27th June, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rabinarayan Biswal
Web Developer
India India
Member
working as a software engineer in mindfiresolutions (http://www.mindfiresolutions.com), Bhubaneswar, a growing IT company of India .
I like solving cryptic codes of C/C++ and spend my leisure in writing poems and reading books.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5 Pinmembermanoj kumar choubey28 Feb '12 - 18:02 
Nice
GeneralMy vote of 5 PinmemberTapeshmittal7 Mar '11 - 1:45 
Simple and easy to understand
Answergcc 64-bit support, and output file never closed Pinmemberx87Bliss21 Feb '10 - 17:46 
The hard-coded "unsigned int" type of many size variables can lead to warnings, and potentially unwanted behavior if compiled as-is with a 64-bit compiler.
 
The best way around this is to replace any "unsigned int" type that refers to the allocated size to a "size_t" type. size_t is automatically defined to be the width of a pointer variable.
 
In report_mem_leak, some sprintf specifiers also need to be changed. Replacing the address and size from "%d" to "%zd" will make sprintf expect an integer the size of size_t.
 
Also, a separate issue in report_mem_leak is that the file handle is never closed. You'll want to add "fclose(fp_write);" after (outside of) the for loop.
QuestionIs there a bug? Pinmemberlindamon11 Dec '09 - 17:10 
very useful code ~~
And I tried it in my project~~
I found a bug(??)
 
ex:
ptr1 = (char *) malloc (10); // allocating 10 bytes
free(ptr1 );
 
ptr2 = (int *) calloc (10, sizeof(int)); // it occurred error~ 'cos ptr_next is freed

and I cehck source code....
it looks like "ptr_next" doesn't update in erase function.
 
Here is my added code
      temp = ptr_start;
      while(temp->next != NULL) 
      {
        temp = temp->next;
      }
      ptr_next = temp;

SuggestionRe: Is there a bug? PinmemberAri Poutanen25 Feb '13 - 1:12 
GeneralMy vote of 1 PinmemberFrank Heimes13 Jan '09 - 23:25 
Too trivial to be useful.
Leaks will be reported in higher level functions that are called many times. Full Call Stack is minimum requirement!
QuestionWhat about realloc? Pinmemberinnqubus15 Jul '08 - 20:43 
I am working on a C code.. which has a dynamic array of structures and again there are nested structures which also have a dynamic array.
I have used realloc extensively through out.
But this code doesn't have anything for realloc function call.
So i can't use this right?
QuestionHow to track the memory leak in when we call a library function (say delivered by some 3rd party) PinmemberRaghu Joshi23 Jun '08 - 7:19 
How to track the memory leak in when we call a library function (say delivered by some 3rd party).
The
#define malloc(x) our_alloc(x, __LINE__, __FILE__)
works only with the code that we compile & build. But not with the called library function which inturn call malloc.
Please let me know the possible solution.
GeneralSimple but yet powerful memory leak detector PinmemberArvind Bharti11 Jul '07 - 23:24 
Few weeks back I have implemented the memory leak detector on same pattern in our code but at that time prime objective was to find the maximum heap size used. You'll be surprised to know that structure members were exactly same.
anyways nice article.
GeneralRe: Simple but yet powerful memory leak detector PinmemberNarain123428 Aug '11 - 20:18 
QuestionIs it great article??? PinmemberAlexander Naumov3 Jul '07 - 3:05 
It seems like author was made first steps on the way to learn programming. His article is not about real-world programming. I.e what about new() operator in C++? What if we don't use that "old-as-world" malloc()?
 
Today I was spend many hours to find a bug in not-my-code. There was a quite stupid bug when a pointer was not set to NULL after free() called on it... Maybe an author of that code, and author of this article - is one person?
 
Pa pouwa Legba Atibon!

AnswerRe: Is it great article??? PinmemberKandjar4 Jul '07 - 10:38 
AnswerRe: Is it great article??? Pinmemberkesselhaus7 Jul '07 - 13:49 
AnswerRe: Is it great article??? PinmemberMeNot9 Jul '08 - 4:30 
QuestionWill it work in C++? PinmemberMichael A. Rusakov3 Jul '07 - 0:17 
Great article, thank you for sharing!
 
Will your code work in C++ with new/delete operators, or it's just for malloc?
 
Thank you!
 
Sincerely,
Michael Rusakov.
http://www.wincatalog.com

AnswerRe: Will it work in C++? PinmemberRabinarayan Biswal3 Jul '07 - 20:20 
GeneralRe: Will it work in C++? PinmemberRaghu Joshi23 Jun '08 - 7:22 
Generalyes gr8 PinmemberMarkandey_Dawn2 Jul '07 - 21:16 
This one is gr8
GeneralGreat Article...see _CRTDBG_MAP_ALLOC on windows PinmemberAnandChavali27 Jun '07 - 21:28 
Great article..absolutely no doubt about that...my 5 for you..
 
But there is also another more common/simplier way than replacing CRT Debug functions espicially in DEBUG(ONLY DEBUG) builds..
 
see _CRTDBG_MAP_ALLOC on windows. By enabling this flag which is defined in crtdbg.h(this is only defined under DEBUG build) one can see the memory leaks and by using _crtBreakAlloc or _CrtSetBreakAlloc you can place a break point at exact location and you can solve the leak issues.Smile | :)
 
Thanks and Regards,
Anand.

GeneralRe: Great Article...see _CRTDBG_MAP_ALLOC on windows PinmemberRabinarayan Biswal27 Jun '07 - 23:27 
GeneralRe: Great Article...see _CRTDBG_MAP_ALLOC on windows PinmemberWes Aday28 Jun '07 - 6:25 
GeneralRe: Great Article...see _CRTDBG_MAP_ALLOC on windows PinmemberJonathan [Darka]28 Jun '07 - 21:33 
GeneralRe: Great Article...see _CRTDBG_MAP_ALLOC on windows Pinmembergiladg223 Jul '07 - 0:10 
GeneralRe: Great Article...see _CRTDBG_MAP_ALLOC on windows PinmemberMeNot9 Jul '08 - 4:47 
Questionvalgrind? PinmemberDaniel Persson27 Jun '07 - 8:29 
Ever heard of valgrind on the *nix platform?
Anyways, nice article.
AnswerRe: valgrind? PinmemberRabinarayan Biswal27 Jun '07 - 23:21 
GeneralRe: valgrind? PinmemberMast Avalons8 Jun '12 - 10:25 
GeneralRe: valgrind? PinmemberSuperMegaCoder12 Jun '12 - 7:46 
GeneralRe: valgrind? PinmemberJohnDepth23 Jul '12 - 8:24 
AnswerRe: valgrind? PinmemberRabinarayan Biswal27 Jun '07 - 23:23 
GeneralRe: valgrind? PinmemberSuperMegaCoder11 Jun '12 - 10:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 27 Jun 2007
Article Copyright 2007 by Rabinarayan Biswal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid