1.

What is a dangling pointer? How to handle it?

Answer»

A dangling pointer is a pointer pointing to a location that was already FREED. De-referencing a dangling pointer causes undefined behaviour.

For example:

struct MyStruct{ int myInt; char myChar;};int main(){ MyStruct* firstPtr = NEW MyStruct(); // .... some code here MyStruct* secondPtr = firstPtr; secondPtr->myInt = 5; secondPtr->myChar = 'A'; DELETE secondPtr; // ... some code here std::cout<<firstPtr->myInt<<" "<<firstPtr->myChar<<"\n";}

In the above example, the secondPtr which points to the same address the firstPtr is pointing to gets deleted and hence later when firstPtr is dereferenced, it gives undefined behaviour. Here the firstPtr becomes a dangling pointer as it is still pointing to the MEMORY that got deleted.

To avoid having dangling POINTERS, we can use smart pointers (or) check all the pointers that are being referenced and explicitly make them NULL so that they don't point to the deleted memory.



Discussion

No Comment Found