Strange bug while concatenating TBytes arrays

Summary

There is a strange issue while concatenating mixture of multiple TBytes variables and constants. The concatenation produces a buggy result.

System Information

  • Operating system: Ubuntu 22.04
  • Processor architecture: x86-64
  • Compiler version: 3.2.2
  • Device: Computer

Steps to reproduce

Cosider x and y as variables of type TBytes. Initiate them as bellow:

x := [1, 2, 3, 4, 6, 7, 8];
y := [];

Now do the following operation:

y := y + [5, x[1]] + copy(x, 3, length(x));

We would expect the result as y = [5, 2, 4, 6, 7, 8] but what happens is y = [4, 6, 7, 8, 4, 6, 7, 8]

Example Project

program Project1;

{$mode delphi}

uses
  SysUtils;

var
  x, y: TBytes;
  i: Integer;
begin
  x := [1, 2, 3, 4, 6, 7, 8];

  y := [];   // y = []
  y := y + [5, x[1]] + copy(x, 3, length(x)); // y = [5, 2, 4, 6, 7, 8]
  for i := 0 to High(y) do begin
    // Expected output:   5 2 4 6 7 8
    // What was written:  4 6 7 8 4 6 7 8
    // ERROR
    Write(y[i]: 2);
  end;
  Writeln;

  y := [5, x[1]];   // y = [5, 2]
  y := [5, x[1]] + y + copy(x, 3, length(x)); // y = [5, 2, 5, 2, 4, 6, 7, 8]
  for i := 0 to High(y) do begin
    // Expected output:   5 2 5 2 4 6 7 8
    // What was written:  4 6 7 8 5 2 4 6 7 8
    // ERROR
    Write(y[i]: 2);
  end;
  Writeln;

  y := [5, x[1]];   // y = [5, 2]
  y := [5, x[1]] + copy(x, 3, length(x)); // y = [5, 2, 4, 6, 7, 8]
  for i := 0 to High(y) do begin
    // Expected output:   5 2 4 6 7 8
    // What was written:  5 2 4 6 7 8
    // Correct
    Write(y[i]: 2);
  end;
  Writeln;

  y := [5, x[1]];   // y = [5, 2]
  y := x + y + copy(x, 3, length(x)); // y = [1, 2, 3, 4, 6, 7, 8, 5, 2, 4, 6, 7, 8]
  for i := 0 to High(y) do begin
    // Expected output:   1 2 3 4 6 7 8 5 2 4 6 7 8
    // What was written:  1 2 3 4 6 7 8 5 2 4 6 7 8
    // Correct
    Write(y[i]: 2);
  end;
end.

What is the current bug behavior?

In case 1 and 2, the output is wrong, but in case 3 and 4 the output is correct. It seems the concatenation of mixture of multiple (more than 2) preinitialized variables with inplace arrays is the cause of the problem.

Relevant logs and/or screenshots

Program output:

 4 6 7 8 5 2 4 6 7 8
 4 6 7 8 4 6 7 8
 5 2 4 6 7 8
 1 2 3 4 6 7 8 5 2 4 6 7 8

Possible fixes

Edited by Vahid Nasehi