{{announcement.body}}
{{announcement.title}}

Dangling Pointer in C++

DZone 's Guide to

Dangling Pointer in C++

Master dangling pointers with this tutorial.

· Web Dev Zone ·
Free Resource

Image title

It's not always easy to understand some concept at first. However, a good analogy can always help you to grasp it and keep remembering it. 

A dangling pointer is one of those concepts. Let me demonstrate with code first, then explain after that with an analogy. 

//Declaring two pointer variables to int
int * ptr1;
int * ptr2;

// Allocating dynamic memory in the heap
ptr1 = new int;
ptr2 = ptr1; // Having both pointers to point same dynamic memory location

//deleting the dynamic memory location 
delete ptr1;
ptr1 = nullptr; 

//ptr2 is still pointing the already deleted memory location 
//We call ptr2 is a dangling pointer


As you have seen code above we have ptr2 pointing to a location that is released to the operating system, if we try to access that memory location we cause nondeterministic behavior. It's a big risk, and it's a bug that waits for the day to show up most likely it will be a very bad day. If we try to release that location once more like delete ptr2, it will crash after throwing an exception. 

You may also like: Optimize Memory Access to Increase Your Coding Performance.

The analogy to understand and helps you to remember is the following:  There is a car a coupel owns that has two keys. The husband caries the one, and the wife carries the other. One day, the husband sells the car without informing her wife; the new owner parks the car at a shopping mall, and the wife notices the car and opens with her key and gets into the car. This happens in front of the new owner of the car, who calls over an officer standing-by about this incident and shouts, "they are stealing my car!"

The situation is exactly the same. If you have two keys (two pointers) to the same car (to same memory location), and you sell the car (release the memory), you should give both keys to the new owner (making both of the pointers to null). Otherwise, getting in the car with the spare key will most likely cause a problem, and if you try to sell it again (delete the memory once again) you could get arrested (Exception - code crash).

I hope this helps with your understanding of dangling pointers in C++.


Further Reading

Topics:
c++

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}