DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Pascal and Delphi (http://www.daniweb.com/forums/forum124.html)
-   -   Delphi SetLength dilemma (http://www.daniweb.com/forums/thread132890.html)

Thew Jul 6th, 2008 6:26 am
Delphi SetLength dilemma
 
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

Duoas Jul 6th, 2008 7:38 am
Re: Delphi SetLength dilemma
 
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.

Thew Jul 6th, 2008 7:42 am
Re: Delphi SetLength dilemma
 
So if I want be sure with deallocating memory, should I use something like FreeMem(Names) ?

Duoas Jul 6th, 2008 7:23 pm
Re: Delphi SetLength dilemma
 
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.

Thew Jul 8th, 2008 7:17 am
Re: Delphi SetLength dilemma
 
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.

Duoas Jul 8th, 2008 7:24 am
Re: Delphi SetLength dilemma
 
No exception because after SetLength(0) the variable is already nil, and FreeMem has a built-in safeguard against freeing nil pointers.


All times are GMT -4. The time now is 7:36 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC