title: Dynamic arrays and memory management in Delphi
body: <p>The following article on dynamic arrays in Delphi says that you allocate a dynamic array using the <code>SetLength()</code> function.</p>
  
  <pre><code>myObjects : array of MyObject;
  ...
  SetLength(myObjects, 20);
  // Do something with the array.
  myObjects := nil;
  </code></pre>
  
  <p><a href="http://delphi.about.com/od/beginners/a/arrays.htm" rel="nofollow">http://delphi.about.com/od/beginners/a/arrays.htm</a></p>
  
  <p>This seems like a memory leak to me:</p>
  
  <p><strong>The question is</strong>, if <code>SetLength()</code> is the equivalent of the C++ <code>MyObject *obs = new MyObject[20]</code>, then arrays are just pointers, so is setting the Delphi <code>myObjects</code> variable to <code>nil</code> the same as setting <code>obj = NULL</code> in C++? I.e., is this a memory leak?</p>
  
  <p><strong>EDIT</strong>: 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 <code>myObj := MyObject.Create</code> and <code>myObj.Free</code>, <code>myObj := nil</code>, 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?</p>
  
  <pre><code>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;
  </code></pre>