Member Avatar for Thew

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

Recommended Answers

All 5 Replies

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 for Thew

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

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 for Thew

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.