Memory leaks

Posted on 2004-09-24
Last Modified: 2013-12-14
Hello All,

How can I develop a tool that will find memory leaks in C code? Yes, I mean programmer allocated dynamically a bunch of memory and forgets to free them. This utility should find there are no references to this and free from heap.

Anybody has any idea??

Question by:Mamata_gd
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +3
LVL 55

Expert Comment

by:Jaime Olivares
ID: 12145086
Take a look to this project with source code:

LVL 45

Expert Comment

by:Kent Olsen
ID: 12145817

Also look at

There are several ways to "write your own" that will help uncover a lot of the basic errors.


Author Comment

ID: 12145824
Is it for Windows system?

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 45

Expert Comment

by:Kent Olsen
ID: 12145967

valgrind doesn't work well with Windows GUI applications.  :(

Do you have any idea how many functions allocate or free memory?  Or how many times malloc() is called?

LVL 23

Expert Comment

ID: 12147757
The main library calls you need to hook around to detect memory leaks in C are malloc and free
To detect other kinds of leaks (like files left open), you may also need to latch onto open() and close()

The thing needing to be checked to determine a leak is that the result of every malloc call is either freed or remains
reachable by a pointer (like it's data information in a data structure while the program is running).

Try looking for Boehm for guidance
it's a garbage collector for C and C++

which is a step beyond what's needed to detect the common leak situation


Expert Comment

ID: 12155711
There are a number of excellent heap allocation and monitoring tools out there.  I used to use a commercial product under Windows called Smartheap which, at the time, had the additional advantage of being much faster than MS's malloc()/free().  Since there was a third party market, I expect that MS has "innovated" some cruddy heap browser into MSVC in the meantime.  I know it prompted them to fix their allocation...

Barring that, the simplest answer and one which might well give you what you need is to wrap malloc() and free() to include a printf or log message.  For example, you could create a function similar to:

malloc_ptr_t mymalloc(size_t size)
        malloc_ptr_t p;
        p = malloc(size);
        printf("malloc(%d)=%lx\n", size, p);
        return (malloc(size));

(caveat: pseudocode off the top of my head...may not compile or work).

and replace all references to "malloc" with "mymalloc" (use a #define but be careful not of affect the fn above).  Do the same for free and now you should be able to match your allocs and frees...

Author Comment

ID: 12163179
Yes, stubbing mallc and free is good idea. But, how do i know that pointer is not referenced for long time or there are no refrence to this allocation. In that case, the untility should go ahead and delete the allocation. how do I do that???

I am interested more in the deletion if not referenced? Meaning, how can I find out that there are no references to this allocation???


Accepted Solution

guynumber5764 earned 25 total points
ID: 12163999
The unfortumate and short answer is you don't because you can't.  What you are asking for is called "automatic garbage collection", a feature that is impossible to implement natively in C.  Its one of the big arguments for using Java.

In C, the only connection between a pointer variable and the heap is malloc()/free().  People have defined smart pointer classes that add  reference counts and/or LRU algorithms but they tend to have limited application and probably wouldn't solve your problem anyways.

The only real solution is to figure out where the memory is coming from and where it is supposed to be freed.  As a bonus, this will probably have the effect of simplifying your design and increasing correctness.  I would suggest starting with a code review that, at every malloc(),  asks the questions: "which object or module "owns" this memory (usually the allocator)" and "When and how does it get released?".
LVL 45

Assisted Solution

by:Kent Olsen
Kent Olsen earned 25 total points
ID: 12164113

There are a couple of "tricks" that you can perform to see just how big the problem really is.  The first, and easiest, is just increment counters every time that malloc() or free() is called.  You probably need to conditionally increment when realloc() is called when passed a zero for the base address, too.

int MallocCount = 0;
int FreeCount = 0;
int ReAllocZeroCount = 0;

void *MyMalloc (size_t size)
  return (malloc (size0);

void MyFree (void *Address)
  free (Address);

void *MyReAlloc (void *Address, size_t *Size)
  if (Address == NULL)
  return (realloc (Address, Size));

Then right before the program exits, display the values of MallocCount, FreeCount, and ReAllocZeroCount.  This will tell you the number of buffers that you've assigned and how many that you've assigned that weren't free()ed.

With some enhancing, you can also learn the number of bytes of heap memory that are still assigned and even the address of the buffers so that you can dump/display them.


Expert Comment

ID: 12277583
In Sun OS, bcheck utility is there ..
bcheck [-access | -all | -leaks | -memuse] [-o logfile ] [-q]  [-s script] program  [args]

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Here is a helpful source code for C++ Builder programmers that allows you to manage and manipulate HTML content from C++ code, while also handling HTML events like onclick, onmouseover, ... Some objects defined and used in this source include: …
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode ( They will have you believe that Unicode requires you to use…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question