为什么释放坏对象指针会抛出 EPrivilege 而不是 EAccessViolation?
当我执行此过程时,为什么会收到“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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
FreeAndNil
调用非虚方法Free
。它首先检查nil
(变量可能不是nil
),然后调用虚拟析构函数Destroy
。调用虚拟方法意味着查看对象的开头以获取虚拟方法表(VMT)。这可能会引发访问冲突。但如果该对象位于分配的内存中,它将返回一个未定义的指针作为 VMT。
接下来,在距 VMT 一定偏移处读取指针大小的值。这可能再次引发访问冲突或返回未定义的指针。
最后执行这个指针指向的内存。如果它碰巧包含无效代码,您会得到无效指令异常的某种变体。
FreeAndNil
calls the non virtual methodFree
. Which first checks fornil
(the variable likely isn'tnil
) and then calls the virtual destructorDestroy
.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.
有时您会遇到访问冲突,有时您会获得
EPrivilege
,毫无疑问还有其他失败模式。甚至有时代码看起来可以工作,但稍后会发生崩溃。这完全取决于当您调用Free
时t
中的值是什么。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 int
when you callFree
on it.