Solved

Memory leaks

Posted on 2004-09-24
13
494 Views
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??

Thanks
M
0
Comment
Question by:Mamata_gd
  • 3
  • 2
  • 2
  • +3
13 Comments
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
Take a look to this project with source code:
http://freshmeat.net/projects/memwatch/?topic_id=47%2C809

0
 
LVL 45

Expert Comment

by:Kdo
Comment Utility

Also look at http://valgrind.kde.org/

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


Kent
0
 

Author Comment

by:Mamata_gd
Comment Utility
Is it for Windows system?

M
0
 
LVL 45

Expert Comment

by:Kdo
Comment Utility

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?

Kent
0
 
LVL 23

Expert Comment

by:Mysidia
Comment Utility
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 http://www.hpl.hp.com/personal/Hans_Boehm/gc/ 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

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 3

Expert Comment

by:guynumber5764
Comment Utility
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...
0
 

Author Comment

by:Mamata_gd
Comment Utility
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???

Thanks,
M
0
 
LVL 3

Accepted Solution

by:
guynumber5764 earned 25 total points
Comment Utility
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?".
0
 
LVL 45

Assisted Solution

by:Kdo
Kdo earned 25 total points
Comment Utility

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)
{
  MallocCount++;
  return (malloc (size0);
}

void MyFree (void *Address)
{
  FreeCount++;
  free (Address);
}

void *MyReAlloc (void *Address, size_t *Size)
{
  if (Address == NULL)
    ReAllocZeroCount++;
  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.


Kent
0
 
LVL 1

Expert Comment

by:manojantony
Comment Utility
In Sun OS, bcheck utility is there ..
bcheck [-access | -all | -leaks | -memuse] [-o logfile ] [-q]  [-s script] program  [args]
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Hide carret in RichEdit 4 49
Fast data scrub 19 88
Insert several multiple frames into a single mainframe 3 46
The line on IDE 4 34
Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
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: …
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

763 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now