为什么释放坏对象指针会抛出 EPrivilege 而不是 EAccessViolation?

发布于 2024-12-28 11:40:52 字数 316 浏览 4 评论 0原文

当我执行此过程时,为什么会收到“EPrivilege - 特权指令”而不是访问冲突

{$Warnings OFF}
procedure TFrmMyTest.mnuCrashMeClick(Sender: TObject);
var t: TStringList;
begin
 FreeAndNil(t);
end;
{$Warnings ON}

我知道我尝试释放内存中随机指向的对象。但我希望得到访问冲突而不是“特权指令”。

(别担心,我不打算在实际程序中使用上面的代码。)

Why do i get an "EPrivilege - Privileged instruction" when I execute this procedure instead of Access Violation?

{$Warnings OFF}
procedure TFrmMyTest.mnuCrashMeClick(Sender: TObject);
var t: TStringList;
begin
 FreeAndNil(t);
end;
{$Warnings ON}

I know that I try to free an object that points randomly in memory. But I expect to get an access violation and not "Privileged instruction".

(Don't worry I don't intend to use the code above in a real program.)

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

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

发布评论

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

评论(2

陪我终i 2025-01-04 11:40:52

FreeAndNil 调用非虚方法Free。它首先检查 nil(变量可能不是 nil),然后调用虚拟析构函数 Destroy

调用虚拟方法意味着查看对象的开头以获取虚拟方法表(VMT)。这可能会引发访问冲突。但如果该对象位于分配的内存中,它将返回一个未定义的指针作为 VMT。

接下来,在距 VMT 一定偏移处读取指针大小的值。这可能再次引发访问冲突或返回未定义的指针。

最后执行这个指针指向的内存。如果它碰巧包含无效代码,您会得到无效指令异常的某种变体。

FreeAndNil calls the non virtual method Free. Which first checks for nil(the variable likely isn't nil) and then calls the virtual destructor Destroy.

Calling a virtual method means looking at the beginning of an object to get the virtual-method-table(VMT). This can throw an access violation. But if the object is in allocated memory, it will instead return an undefined pointer as VMT.

Next a pointer sized value is read at a certain offset from the VMT. This once again can throw an access violation or return an undefined pointer.

Finally the memory where this pointer points is executed. And if it happen to contain invalid code, you get some variant of an invalid instruction exception.

旧人哭 2025-01-04 11:40:52

有时您会遇到访问冲突,有时您会获得EPrivilege,毫无疑问还有其他失败模式。甚至有时代码看起来可以工作,但稍后会发生崩溃。这完全取决于当您调用 Freet 中的值是什么。

Sometimes you will get an access violation and sometimes you will get EPrivilege and no doubt there are other modes of failure. And even sometimes the code will appear to work and the crash will happen later. It all depends on what value happens to be in t when you call Free on it.

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