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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With