Application.Terminate 产生访问冲突错误 Delphi 10.3

发布于 2025-01-15 14:54:31 字数 1019 浏览 1 评论 0原文

一旦创建了 TImage 动态数组,Application.Terminate() 过程就会导致访问冲突。

数组(可变长度):

arrImages: array of TImage;

访问冲突:

Access violation at address 00405D39. Write of address 004680EC

由于这种情况仅在创建动态数组后发生,因此我尝试释放数组中的所有元素(onTmrImage 是一个全局变量,包含数组中的第一个元素数组,数组中的元素都是 GUI 上的动态 TImage 组件):

procedure TfrmTank.procPurgeArray;
var
  I: integer;
begin
  FreeAndNil(onTmrLImage);
  for I := 1 to length(arrImages) do
  begin
    FreeAndNil(arrImages[I]);
  end;

  FreeAndNil(arrImages);

end;

然后在 onClick 事件中使用 Application.Terminate()退出按钮:

procedure TfrmTank.btnExitClick(Sender: TObject);
begin
  procPurgeArray;
  Application.Terminate;
end;

知道为什么吗是否有必要做任何事情来简单地退出应用程序?

The Application.Terminate() procedure causes an Access Violation once a dynamic array of TImage has been created.

Array (variable length):

arrImages: array of TImage;

Access violation:

Access violation at address 00405D39. Write of address 004680EC

Since this only occurs after the dynamic array has been created, I have tried to free all elements in the array (onTmrImage is a global variable containing the first element in the array, the elements in the array are each dynamic TImage components on the GUI):

procedure TfrmTank.procPurgeArray;
var
  I: integer;
begin
  FreeAndNil(onTmrLImage);
  for I := 1 to length(arrImages) do
  begin
    FreeAndNil(arrImages[I]);
  end;

  FreeAndNil(arrImages);

end;

And then used Application.Terminate() in the onClick event of the exit button:

procedure TfrmTank.btnExitClick(Sender: TObject);
begin
  procPurgeArray;
  Application.Terminate;
end;

Any idea as to why it is necessary to even do anything to simply exit the application?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱桃奶球 2025-01-22 14:54:31
freeandnil(arrImages);

这是一个错误。您不得对动态数组调用Free。您可以对对象实例调用Free。将此行代码替换为 arrImages := nil

动态数组会自动销毁,因为它们是托管类型。

销毁图像时,您还会得到错误的数组索引。动态数组是从零开始的。您的循环应该是:

for I := 0 to High(arrImages) do
  arrImages[I].Free;
arrImages := nil;

也许创建数组的代码中也存在同样的错误。

综上所述,这段代码肯定属于析构函数。有人甚至可能会说,当您即将执行 Application.Terminate 时,这有点毫无意义。

freeandnil(arrImages);

This is a bug. You must not call Free on a dynamic array. You can call Free on an object instance. Replace this line of code with arrImages := nil.

Dynamic arrays are destroyed automatically because they are managed types.

You also get the array indices wrong when destroying the images. Dynamic arrays are zero-based. Your loop should be:

for I := 0 to High(arrImages) do
  arrImages[I].Free;
arrImages := nil;

Perhaps the same mistake is present in the code that creates the array.

With all this said, surely this code belongs in a destructor. And one could even argue that it's a little pointless when you are about to do Application.Terminate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文