Kanade's Delphi Stuff
Delphi Tips, Sample code and Tools
Copyright © 1997-2004, Sanjay Kanade
 
  Tips and Tricks on Delphi
Please read the DISCLAIMER before you use any of the tips from this web site. Go to main index
  Delphi Tips: Memory leaks
Tip 58:  MemCheck, a great tool
(modified: 19 May 2002)


Tip 2:  Memory leak in sample or supplied code
(modified: 16 Feb 2001)


  58: MemCheck, a great tool
Date added/modified: 19 May 2002

Recently, I had to trace a memory leak in one of my applications, and I searched the web for a Delphi utility. Finally, I found one and used it successfully to debug the problem. It's called MemCheck, and I highly recommend it.
http://v.mahon.free.fr/pro/freeware/memcheck/

  2: Memory leak in sample or supplied code
Date added/modified: 16 Feb 2001

It may be difficult to catch memory leaks. But, sometimes, memory leaks come into your program by faulty examples or even sample code which you never suspect! I got hit by a sample code in the FmxUtils unit which I happened to copy and use in my own code.

Here is a function in the FmxUtils supplied with Delphi 3 (corrected in Delphi 5 now):

function GetFileSize(const FileName: string): LongInt;
var
  SearchRec: TSearchRec;
begin
  if FindFirst(ExpandFileName(FileName), faAnyFile, SearchRec) = 0 then
    Result := SearchRec.Size
  else Result := -1;
end;
Can you spot the memory leak there? In Win32, a FindFirst call should always have a corresponding FindClose. Otherwise, it will cause a memory leak! If you have used this function, check everywhere. If you used the pair of FindFirst and FindNext in the traditional way in a loop, then you will most probably have a FindClose after the FindNext loop. No problem in that case. But, watch out for single use of FindFirst, used just to get file size or attributes.

A word of caution: Earlier, I was under the impression that calling FindClose even on failure of FindFirst doesn't cause any harm. This appears OK as far as my test on Windows 95 goes. But, according to Brad Stowers, it will lock up an NT application. So, it would be safer not to call FindClose on the failure of FindFirst.

See the fixed code for this in the sample code area.



 

Copyright 1995-2004, Sanjay Kanade. All rights reserved.
All trademarks and copyrights belong to their respective owners.