Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using SetLength() in Delphi, what is the proper way to deallocate that memory?

Tags:

arrays

delphi

I recently was looking at some code that uses SetLength to allocate memory for an array of bytes, but I didn't see any logic to release that memory space. I have read that for an array of bytes you should either set the value to nil or use Finalize?

What is the best way to handle this... Based on what I found it suggests something like the following...

var
  x: array of byte;
begin
  SetLength(x, 30);
  // Do something here
  :
  // Release the array
  x := nil;
  Finalize(x);
end;
like image 663
Tim Koscielski Avatar asked May 18 '12 16:05

Tim Koscielski


2 Answers

Normally, you don't need to free the memory at all, since this is done automatically when the identifier (in this case, x) goes out of scope. Hence, the two last lines in your code are completely meaningless.

If, however, you have an identifier that does not go out of scope until, say, your program is closing, then you might wish to free the memory associated with it manually. In particular, you might want to do this if the identifier is a large bitmap image or something like that. Then you could do x := nil, SetLength(x, 0) or something like that.

like image 138
Andreas Rejbrand Avatar answered Nov 15 '22 20:11

Andreas Rejbrand


Dynamic arrays are managed types. This means that the compiler will dispose of the memory when the last reference to the array goes out of scope. That means that the code to free the array in your code is rather pointless.

If you need to, you can deallocate the array ahead of time by using any of these equivalent lines of code:

SetLength(x, 0);
Finalize(x);
x := nil;

Beware that if you have mutiple references to the same array then you need to do this for all references to that array.

like image 34
David Heffernan Avatar answered Nov 15 '22 20:11

David Heffernan