如何避免 FPC 编译器上的 SIGSEGV 错误?

How to avoid SIGSEGV Errors on FPC compiler?

我目前在为我的编程课程构建的程序中遇到一些访问冲突问题。它是用 Pascal(课程使用的语言)构建的,并使用 Lazarus IDE(类似于 Delphi 但开放)。

据我所知,当您尝试使用或寻址无效内存位置时,会发生访问冲突或 SIGSEGV 错误。我经历过很多这样的情况,特别是当我没有声明动态数组的长度时。

现在看来我遇到了字符串问题。 (或者我可能对多维数组感到困惑)。

我将只粘贴 SIGSEGV 指向的过程,但上下文是:

我有一个整数数组和一个包含它的幂集的多维数组(subconjuntos),出现错误的函数(如下所述)用于打印此电源设置为 TextBox(由 local 索引):

procedure writeSub(local: TEdit);
var
  i, j: integer;
begin
 for i:= 0 to High(subconjuntos)+1 do
   if Length(subconjuntos[i])>1 then
   begin
     local.Text:=local.Text+'[';
     for j:=0 to High(subconjuntos[i])+1 do local.Text:=local.Text+'('+IntToStr(subconjuntos[i][j])+') ';
     local.Text:=local.Text+'] ';
   end
   else local.Text:=local.Text+'['+IntToStr(subconjuntos[i][0])+'] '; {this is where I'm having the SIGSEG, the program wont compile if I don't reference it without the double brackets}
end;  

知道它为什么抛出 SIGSEGV 吗?

动态数组的有效索引在 low(arr)high(arr) 范围内(含)。并且 low(arr) 对于动态数组始终为零。您试图访问索引为 high(arr)+1 的元素。那超出了数组的末尾,当然是一个错误。

你写的地方

for i:= 0 to High(subconjuntos)+1 do

应该是

for i:= 0 to High(subconjuntos) do

for i:= Low(subconjuntos) to High(subconjuntos) do

你的其他循环也是如此。

此外,如果 Length(subconjuntos[i]) 为零,则 subconjuntos[i][0] 是越界访问。

如果您在编译器选项中启用范围检查,那么编译器将发出代码来检查每个数组访问的有效性。这样做会导致您更快地出现此类错误。