The following article on dynamic arrays in Delphi says that you allocate a dynamic array using the SetLength()
function.
myObjects : array of MyObject;
...
SetLength(myObjects, 20);
// Do something with the array.
myObjects := nil;
http://delphi.about.com/od/beginners/a/arrays.htm
This seems like a memory leak to me:
The question is, if SetLength()
is the equivalent of the C++ MyObject *obs = new MyObject[20]
, then arrays are just pointers, so is setting the Delphi myObjects
variable to nil
the same as setting obj = NULL
in C++? I.e., is this a memory leak?
EDIT: I understand from David's answer that the compiler manages memory for dynamically allocated arrays. I also understand from his answer than the compiler does manage memory for ordinary class instances (hence the use of myObj := MyObject.Create
and myObj.Free
, myObj := nil
, etc). Also, because Delphi classes (not records) are always allocated on the heap (Delphi using a kind of reference/pointer system), does that mean that all the objects within the (automatic memory-managed) dynamic array still need to be memory-managed by me? E.g., does the following cause a fault by double freeing a result?
myObjects : array of MyObject;
...
SetLength(myObjects, 20);
for i := 0 to 19 do
begin
myObjects[i] := MyObject.Create;
end;
// Do something with the array.
// Before de-allocating it, if I *know* I am the only user of the array,
// I have to make sure I deallocate each object.
for i := 0 to 19 do
begin
myObjects[i].Free;
myObjects[i] := nil; // Redundant, but for illustrative purposes.
end;
myObjects := nil;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…