gpt4 book ai didi

delphi - 为什么访问动态数组的越界索引不会引发 AV?

转载 作者:行者123 更新时间:2023-12-03 15:47:49 32 4
gpt4 key购买 nike

在VCL中,TByteDynArray被定义为动态数组:

type TByteDynArray = array of Byte;

但似乎没有完成索引边界检查:

var
DataBytes: System.Types.TByteDynArray;
i: Integer;
begin
SetLength(DataBytes, 2);
DataBytes[5] := 222; // Accessing index beyond set length.
i := DataBytes[5]; // `i` is now set to "222".

上面的代码运行没有错误。

为什么没有像静态数组那样引发 AccessViolation ?如果无论设置的长度如何,都可以访问和修改数组变量的 65536 字节内存,那么 SetLength 的意义何在?

最佳答案

要检测数组索引越界错误,请将范围检查错误设置为打开。

Range Checking

The $R directive enables or disables the generation of range-checking code. In the {$R+} state, all array and string-indexing expressions are verified as being within the defined bounds, and all assignments to scalar and subrange variables are checked to be within range. If a range check fails, an ERangeError exception is raised (or the program is terminated if exception handling is not enabled).

默认设置为 {$R-},但我建议至少在开发阶段将其设置为打开状态。它给代码增加了额外的开销,因此这可能是它默认关闭的原因。

<小时/>

如果您有一个经过充分测试的单元并且希望避免范围检查,请在单元顶部添加 {$R-}。这将覆盖本地的项目设置。

如果您想避免在代码块中进行范围检查,可以使用此技术:

{$IFOPT R+}
{$DEFINE RestoreRangeCheck}
{$R-}
{$ENDIF}

{- Some code here }

{$IFDEF RestoreRangeCheck}
{$R+}
{$UNDEF RestoreRangeCheck}
{$ENDIF}

关于delphi - 为什么访问动态数组的越界索引不会引发 AV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33210275/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com