Fixing memory leaks

Started by
10 comments, last by Ratman 22 years, 9 months ago
Aside from "not writing them in the first place" what is a good way to track down memory leaks? I have a feeling my program has a few, but have no idea where they are. Are there any tools/tricks/etc you guys use to track them down? or is it pretty much going through all your code and making sure you clean up everything? Thanks ratman
Advertisement
There''s lots of software available you can use, such as Electric Fence, BoundsChecker, Purify, and so on. A search for memory leak detectors or whatever on a search engine should find some for you. They range from being freeware and open source to expensive applications. I used one called HeapAgent which is quite nice and had a (short) free trial. Annoyingly though, it had some sort of bug and stopped working properly after a few days. I talked to the tech support guy but he had no clue how to fix it. So I gave up, and certainly wouldn''t buy the product
Purify and BoundsChecker are both great, and catch memory leaks as well as a bunch of other potential run-time problems. They cost a relative fortune though. Far more than most hobbiest developers can afford (hundreds to thousands of dollars).

I haven''t had any experience with the free programs/libraries, such as Electric Fence.

You can actually use Visual C++ to help you track down memory leaks or use a higher level memory management library in your projects. Check out some of the Code of the Days and older Ask Midnight''s on flipcode (http://www.flipcode.com) for specific information.
MSVC 6 has an easy way to track memory leaks. Just include the following headers and put the next 3 lines in your startup or Winmain.

  ...at top of main file#define _CRTDBG_MAP_ALLOC#include <stdlib.h>#include <crtdbg.h>...in winmainint flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Get current flagflag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit_CrtSetDbgFlag(flag); // Set flag to the new value*/  


Now do a debug build (F5) and at the end you will get a list of memory leaks. If you are using typical C malloc/free, it will give you the line and file the memory was allocated in. If you are using C++ new/delete on classes with constructors, it will tell you same line and file each time, but its better than nothing.
To avoid memory leaks there are some basic rules you should follow:
- use STL (e.g. use std::string instead of char*, use std::vector instead of build in arrays like object[123][456])
- make shure you have a "delete" for every "new"
- keep your code as local as possible

You don''t have to do all this. But if you don''t want to have those little bas***** in your memory eating all of your memory and blocking it from other apps, try to use them.
Visit:http://www.evildawncrew.comAll things which are worth beeing done, are worth beeing donw well.
In C, you can just make functions to do all your allocating, and in C++ you can overload new/delete.

For example..

void* Malloc( int Size, int ReferenceID )
{
// Record in an array/list the ReferenceID and Size, and any other information you want to send
return malloc( Size );
}

void Free( void* AllocatedMemory, int ReferenceID )
{
// Remove the ReferenceID/Size from the array/list

free( AllocatedMemory );
}

When your program closes, check the list and output the results. This will help you track down where you''re allocating and not freeing.

Much more realistic than hobby developers buying hundreds of dollars software : )

G''luck,
-Alamar
as mentioned above, there was a great tip-of-the-day about this at flipcode, check it out:

http://www.flipcode.com/cgi-bin/msg.cgi?showThread=Tip-DetectingMemoryLeaks&forum=totd&id=-1
whats a memory leak?

X4J
X4J
All these tools & tips are great, but I think there''s a problem more insidious than the bona-fide "leak" where memory is not deallocated before the program ends. We''ve had the unfortunate experience once or twice of using container that automatically grow without bounds and release memory once they''re destroyed. The problem is, if they''re really growing without bounds, you can overflow your memory and kill your system resources, even if you deallocate the memory at the end of the program --this does not show up in bounds checker or any "leak detection" utility.

This kind of memory behavior is best detected by running your program with a memory diagnostic tool running. WinNT comes with a great little tool called "Performance Monitor" which can attach to a process and show you handle counts, thread counts, memory allocations, CPU usage, etc. The built-in system monitor for Win98 isn''t adequate for this purpose, but I''m sure there''s some public-domain tools out there that will accomplish the same things. Basically, you want to run your program with this tool running, and if you see a straight slope upward on anything, you have a problem.
To avoid memory leaks, don''t use MFC.
[I did absolutely nothing, and it was everything that I thought it could be]

This topic is closed to new replies.

Advertisement