问题描述
大家好,
我对在指针别名中验证悬空指针有疑问
Hi all,
I have a doubt about verifying a dangling pointer in pointer aliasing
CMyClass* pObj = new CMyClass();
pObj将在其中存储变量的地址(例如K).即pObj指向存储在地址K的变量.
虽然pObj本身将有一些地址(例如X).
pObj will store address (say K) of a variable in it. i.e. pObj pointing to variable stored at address K.
While pObj itself will have some address (say X).
CMyClass* pMirrorObj = pObj; //Aliased Pointer
pMirrorObj还将在其中存储相同变量的地址.即pMirrorObj也指向存储在地址K的变量.
如果我没记错的话,pMirrorObj的地址可能会有所不同(例如Y).
如上所述,
X-> K
Y-> K
我在不同的代码位置使用了两个指针(pObj和pMirrorObj).
pMirrorObj will also store address of same variable in it. i.e. pMirrorObj also pointing to variable stored at address K.
If I am not wrong, pMirrorObj may have some different address (say Y).
As per the above,
X -> K
Y -> K
I am using both pointers (pObj and pMirrorObj) in different code location.
if( pObj )
{
delete(pObj);
pObj = NULL;
}
以上操作结果,
X-> NULL
Y-> K
如何处理第二个指针(悬空指针)?
我应该使用双指针(CMyClass ** ppMirrorObj =& pObj)而不是单指针(pMirrorObj)来避免删除悬空指针的情况,如下所示,
Result of above operation will,
X -> NULL
Y -> K
How to deal with second pointer (dangling pointer)?
Shall I use as double pointer (CMyClass** ppMirrorObj = &pObj) instead of single pointer (pMirrorObj) to avoid deletion dangling pointer as follows,
if( pMirrorObj ) //assigning NULL to pObj, will not make pMirrorObj as NULL
{
delete(pMirrorObj);
pMirrorObj = NULL;
}
谢谢&问候,
Aniket A. Salunkhe
Thanks & Regards,
Aniket A. Salunkhe
推荐答案
CMyClass* pObj = new CMyClass(); // Pointer to object
CMyClass** ppMirrorObj = &pObj; // Pointer to pointer to object
现在您可以:
Now you can:
delete (*ppMirrorObj); // Deletes object pObj points to
*ppMirrorObj = NULL; // pObj now NULL
或
OR
delete (pObj); // Deletes object pObj points to
pObj = NULL; // pObj now NULL
删除NULL指针无效,因此无需检查NULL.
Deleting a NULL pointer has no effect so no need to check for NULL.
这篇关于在指针别名中验证悬空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!