1 year ago
#361742
P.Miz
The way prevent unintended dynamic array pointer changed
Using dynamic array and I noticed unintended perform. My code is below. It's executable as console application.
program Test;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Types;
type
TPointArray = array of TPoint;
var
FPointArray, FDummy1 : TPointArray;
procedure AddPoint(const srcPoint: TPoint; var srcPointArray: TPointArray);
var
i, n : Integer;
begin
Writeln( '1: @srcPoint:' + IntToHex( Cardinal( @srcPoint ), 8 ) + ', ' + '@FPointArray[0]:' + IntToHex( Cardinal( @FPointArray[0] ), 8 ) );
n := Length(srcPointArray);
SetLength(FDummy1, 1);
SetLength(srcPointArray, n + 10000);
Writeln( '2: @srcPoint:' + IntToHex( Cardinal( @srcPoint ), 8 ) + ', ' + '@FPointArray[0]:' + IntToHex( Cardinal( @FPointArray[0] ), 8 ) );
Readln;
end;
begin
SetLength(FPointArray, 1);
FPointArray[0].X := 100;
FPointArray[0].Y := 200;
AddPoint(FPointArray[0], FPointArray);
end.
My project has more amounts of codes, and sometimes access violation caused from other codes. Above code is simple code, so It may not be caused access violation. But I could see the unexpected process.
For example: At the beginning line of AddPoint procedure, @srcPoint is $25E92F8. @FPointArray[0] is $25E92F8. There are same pointer.
After passed below line.
SetLength(srcPointArray, n + 10000);
@FPointArray[0] is changed to $25C6F28. (because of reallocation memory) But @srcPoint is still $25E92F8.
So argument, srcPoint points to invalid memory location. My project has many codes around here, so this address change leads to access violation in result.
Is there any way to avoid this, or can I only do is pay attention not to write such a code?(for example, give up to use "const" option).
Thanks.
arrays
delphi
dynamic
delphi-11-alexandria
0 Answers
Your Answer