Delphi code fails at 64 bits access violation

Viewed 434

This Delphi code works when compiled for 32 bits, but gives an access violation when compiled for 64 bits. Is there a problem with the code, or is there a compiler bug?

{$APPTYPE CONSOLE}

uses
  SysUtils;

const
  MaxSize = 2; // nothing special about this value, could equally be 1

type
  TArraySize = 1..MaxSize;

procedure Main;
var
  size: TArraySize;
  arr: array [-MaxSize..MaxSize] of Integer;
begin
  FillChar(arr, SizeOf(arr), 0); // zero initialize
  size := MaxSize;
  Writeln(arr[-size]);
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.
2 Answers

This is a compiler bug. The compiler does not handle

arr[-size]

correctly, presumably because size is a subrange type.

You can workaround the bug by forcing the compiler to perform the arithmetic in an Integer context.

arr[-Integer(size)]

You should submit a bug report to Embarcadero's Quality Portal.

Update

I tested this in XE7. According to a comment, the defect appears to have been fixed at least in Seattle.

A compiler which gives a Access Violation-error is always having a bug. A compiler should never do that but handle every occurring error gracefully.

Related