Originally Posted by
Cleaner
So dangling pointer can happen if 1 or more than 1 objects point at the same memory location?
I'm not sure if you're thinking the right thing, but you worded it wrong. Objects don't "point" at memory locations. Objects occupy memory locations. Only one object can live at any memory location at any one time. You can, however, have multiple pointers point to the same memory location, but that in itself doesn't create dangling pointers.
Simplest example for a dangling pointer:
Code:
int* ptrToAnInt = new int; // here we create an integer and assign its address to our pointer
delete ptrToAnInt; // <-- from this point on, the integer that used to live at the location pointed to by ptrToAnInt is no longer there
*ptrToAnInt = 5; // <-- UNDEFINED BEHAVIOR! There is no longer an integer at the location pointed to by ptrToAnInt.
P.S. To avoid dangling pointers, you want to set pointers to null the moment the thing they point to stops existing:
Code:
int* ptrToAnInt = new int;
delete ptrToAnInt;
ptrToAnInt = 0; // <-- IMPORTANT! Set pointer to null to make it unmistakably clear that it no longer points to anything.
if ( ptrToAnInt ) // <-- Then check pointer for null before trying to dereference it.
{
*ptrToAnInt = 5;
}