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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With