Marcela Rocha
Marcela Rocha

Reputation: 79

ERangeError on Delphi XE

I'm migrating a software from Delphi 5 to Delphi XE. I've already corrected a lot of differences, and i can now compile my code.

The problem happening is that sometimes (in some places of the code), I'm getting the error "Range Check Error".

For exemple, in this code:

function CopyChar(Ori : string; var Des : Array of char) : Boolean;
var Msg     : string;
    Counter : integer;
    SizeDes : integer;
begin
    SizeDes:= SizeOf(Des);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= ' ';
    end;
    Ori:= Trim(Ori);
    Msg:= '';
    SizeDes:= Min(Length(Ori),SizeDes);
    for Counter:= 1 to SizeDes do begin
        Des[Counter-1]:= char(Ori[Counter]);
    end;
    CopyChar:= True;
end;

I get the error at runtime when passing by the line Des[Counter-1] := ' '; The error occurr not at the first time it passes through the loop, but after lot of times.

I've tried to disable Rance Checking ($R) but it does nos solves my problem. I've also tried to change the type of "Counter" to Cardinal and LongWord, with no success

I would be glad for any helpful idea!

Thanks.

Upvotes: 1

Views: 1743

Answers (2)

Jens Mühlenhoff
Jens Mühlenhoff

Reputation: 14873

Another problem could be a corrupted input of either Ori or Des, so if the problem is not solved by Davids solution, you should check the calling code, too.

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 612954

The code should read something like this:

function CopyChar(Ori : string; var Des : Array of char) : Boolean;
var Msg     : string;
    Counter : integer;
    LenDes  : integer;
begin
    LenDes:= Length(Des);
    for Counter:= 1 to LenDes do begin
        Des[Counter-1]:= ' ';
    end;
    Ori:= Trim(Ori);
    Msg:= '';
    LenDes:= Min(Length(Ori),LenDes);
    for Counter:= 1 to LenDes do begin
        Des[Counter-1]:= char(Ori[Counter]);
    end;
    CopyChar:= True;
end;

I guess your problem is to do with Char now being 2 bytes wide (in Delphi 5 it was 1 byte wide) although I have never used SizeOf on an open array and don't even know what it does!

There are a couple of other issues with this code. The return value seems a little pointless since it can only ever return True. It could also be somewhat compressed like so:

procedure CopyChar(Ori: string; var Des: array of char);
var
  i: Integer;
begin
  Ori := Trim(Ori);
  for i := 1 to Length(Des) do begin
    if i<=Length(Ori) then
      Des[i-1] := Ori[i];
    else
      Des[i-1] := ' ';
  end;
end;

Upvotes: 5

Related Questions