When you use SetLength () in Delphi, what is the best way to unassign this memory?


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...

  x: array of byte;
  SetLength(x, 30);
  // Do something here
  // Release the array
  x := nil;

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.