title: Dynamic array causing an invalid pointer exception
body: <p>I have a procedure that takes a dynamic array <code>TData = TArray&lt;Byte&gt;</code> as a parameter.</p>
  
  <pre><code>procedure DoStuff(const Input: TData);
  begin
    // do nothing
  end;
  </code></pre>
  
  <p>And a function that returns a dynamic array.</p>
  
  <pre><code>function SomeData: TData;
  begin
    Result := [1, 2];
  end;
  </code></pre>
  
  <p>When I use the procedure in the example below, DoStuff gets the following data (1, 2, 3, 1, 3) but I get an EInvalidPointer exception after DoStuff completes. </p>
  
  <pre><code>procedure TForm1.Button1Click(Sender: TObject);
  begin    
    DoStuff([1, 2, 3] + SomeData);
  end;
  </code></pre>
  
  <p>Calling <code>DoStuff([1, 2] + SomeData);</code> does not result in an error, it seems to get touchy when the array is greater than 4 items. If I use a temp variable to hold the array, DoStuff still gets (1, 2, 3, 1, 2) but there is no error.</p>
  
  <pre><code>procedure TForm1.Button2Click(Sender: TObject);
  var
    Temp: TData;
  begin
    Temp := [1, 2, 3] + SomeData;
  
    DoStuff(Temp);
  end;
  </code></pre>
  
  <p>It looks like pointer exception is related to how one of the dynamic arrays are freed when they fall out of scope.</p>
  
  <p>Should I not be using dynamic arrays in this way? When working, this solved my current problem very cleanly. </p>
  
  <p>I also have tried using <code>array of Byte;</code> instead of <code>TArray&lt;Byte&gt;;</code> but had the same result.</p>
  
  <p>Full test unit:</p>
  
  <pre><code>unit Main;
  
  interface
  
  uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
    System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
  
  type
    TData = TArray&lt;Byte&gt;;
  
    TForm1 = class(TForm)
      Button1: TButton;
      Button2: TButton;
      procedure Button1Click(Sender: TObject);
      procedure Button2Click(Sender: TObject);
    private
      { Private declarations }
    public
      { Public declarations }
    end;
  
  procedure DoStuff(const Input: TData);
  function SomeData: TData;
  
  var
    Form1: TForm1;
  
  implementation
  
  {$R *.dfm}
  
  procedure TForm1.Button1Click(Sender: TObject);
  begin
    DoStuff([1, 2, 3] + SomeData);
  end;
  
  procedure TForm1.Button2Click(Sender: TObject);
  var
    Temp: TData;
  begin
    Temp := [1, 2, 3] + SomeData;
  
    DoStuff(Temp);
  end;
  
  procedure DoStuff(const Input: TData);
  begin
    // do nothing
  end;
  
  function SomeData: TData;
  begin
    Result := [1, 2];
  end;
  
  end.
  </code></pre>