1,105,633 Community Members

Delphi SetLength dilemma

Member Avatar
Thew
Junior Poster in Training
61 posts since Jan 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hello,
does the SetLength function in Delphi called with the second argument 0 free the memory used for the array?
Example:

var
  Names: array of String;
  i: Byte;

SetLength(Names,10);
for i:=0 to 9 do
  Names[i] := '...';

SetLength(Names,0);  // << does this code free memory used by Names array ?

and if this doesn't work, how can I free memory for array...
Thanks

Member Avatar
Duoas
Postaholic
2,039 posts since Oct 2007
Reputation Points: 1,022 [?]
Q&As Helped to Solve: 229 [?]
Skill Endorsements: 10 [?]
Featured
 
0
 

All objects in Delphi, including 'string', are allocated on the heap. When you resize a dynamic array the unused objects are automatically destructed for built-in types only -- so in this case, yes.

When you set the length of a dynamic array to zero the dynamic array object itself is also freed and its value becomes nil.

However, deallocating an object does not necessarily mean that Delphi returns memory to the system.

Hope this helps.

Member Avatar
Thew
Junior Poster in Training
61 posts since Jan 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

So if I want be sure with deallocating memory, should I use something like FreeMem(Names) ?

Member Avatar
Duoas
Postaholic
2,039 posts since Oct 2007
Reputation Points: 1,022 [?]
Q&As Helped to Solve: 229 [?]
Skill Endorsements: 10 [?]
Featured
 
0
 

No. That will cause a system exception.

You have very little control over exactly how much memory is used by your application. I believe there are compiler directives to specify the maximum heap size, but I've never had occasion to use them under Win32.

Member Avatar
Thew
Junior Poster in Training
61 posts since Jan 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I tried to call FreeMem(Names) after I set it with SetLength(Names,0), no exception. I think that after I set length of array to zero, system will automaticaly frees the memory used for this array.

Member Avatar
Duoas
Postaholic
2,039 posts since Oct 2007
Reputation Points: 1,022 [?]
Q&As Helped to Solve: 229 [?]
Skill Endorsements: 10 [?]
Featured
 
0
 

No exception because after SetLength(0) the variable is already nil, and FreeMem has a built-in safeguard against freeing nil pointers.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article