1.11M Members

Delphi SetLength dilemma

 
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

 
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.

 
0
 

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

 
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.

 
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.

 
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 six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article