在指针别名中验证悬空指针 [英] Verifying a dangling pointer in pointer aliasing
问题描述
大家好,
我对在指针别名中验证悬空指针有疑问
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 =新的CMyClass();
然后,您可以创建2个指向pObj的指针,而不必复制存储在pObj中的值.
CMyClass ** ptrToOrigPtrA =&pObj;
CMyClass ** ptrToOrigPtrB =&pObj;
如果然后删除(pObj)并将pObj = NULL设置,则* ptrToOrigPtrA和* ptrToOrigPtrB都将为NULL.
因此,由于您可以看到它们指向一个持有NULL的内存位置,因此您知道尝试通过** ptrToOrigPtrA或** ptrToOrigPtrB引用原始对象将是一个坏消息.
所以,是的-您应该使用双指针". :)
Well, you could create a pointer to the new object
CMyClass *pObj = new CMyClass();
Then instead of copying the value stored in pObj, you can create 2 pointers to pObj.
CMyClass **ptrToOrigPtrA = &pObj;
CMyClass **ptrToOrigPtrB = &pObj;
If you then delete(pObj) and set pObj = NULL, then both *ptrToOrigPtrA & *ptrToOrigPtrB will also be NULL.
So, since you can see that they point to a memory location holding NULL you then know that trying to reference the original object via **ptrToOrigPtrA or **ptrToOrigPtrB will be bad news.
So, yes - you should use ''double-pointers''. :)
您可以看看智能指针(例如,参见 ^ ] ).
You may have a look at smart pointers (see, for instance Wikipedia[^]).
您差一点就拥有了.
You nearly had it.
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.
这篇关于在指针别名中验证悬空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!