Newsgroups : Borland : borland.public.delphi.rtl.win32 : 2005 Aug : Dynamic Array Memory Allocation Question.

www.cryer.info
Managed Newsgroup Archive

Dynamic Array Memory Allocation Question.

Subject:Dynamic Array Memory Allocation Question.
Posted by:"Tim H" (timhilt..@hotmail.com)
Date:11 Aug 2005 13:23:00

I am developing an app that will process a large number of binary data
files and I am concerned about creating a memory leak.

The app creates a thread object which reads a data file into some
internal variables does some processing and identifies files that need to
be looked at by an engineer.  It's fairly complex but I will try to
simplify it as much as I can here.

Some of the properties of the object look like this:

    UnitID: String;
    NumberOfReadings: Word;
    Readings: array of TReading;
    
The TReadings is just a 26 byte packed record.  When the file is
processed, first I read the UnitID which is stored in the file as a null
terminated string, then I read the number of readings.  This is from a
Motorola processor so I have to do a conversion, but that isn't really
relevant to the problem.

Once I know how many records I am expecting, I use SetLength
(Readings,NumberOfReadings) to allocate the array.  Then I simply read
through the file loading the array:

    for I := 0 to Pred(NumberOfReadings) do
      Readings[i] := GetNextReading;

So far so good.  I process the data, write out results to a log file, and
move files of interest to another directory and destroys itself.

I want to know what I NEED to do to clean up properly.  I know when the
app terminates Windows will clean up any memory leaks, but a new object
is created for each file which could easily happen 10,000 times before
the application is restarted.

My thought was that when I destroy the object it would automatically
dispose of the dynamic array.  A coworker disagrees and says I must use
SetLength(Readings,0) or I will have a memory leak.

So far I haven't noticed a problem, but the machine has a lot of RAM.

I am also concerned about another app that does something similar but
uses an "array of AnsiString".  Should I be iterating through the array
and setting the length of each string to 0, then set the length of the
array to 0?

Not that it it a huge deal, I could just add the code whether it is
needed or not.  I just wanted to know what was the correct way to handle
it.  In the Delphi docs, it is unclear to me...

Replies:

www.cryer.info
Managed Newsgroup Archive