www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C++ Tutorial - Lesson 19: Dynamic Memory Allocation

Dangling Pointers

by John Kopp

Support this site at no cost to you

Dangling Pointers
Take a look at this snippet of code.

int *myPointer;

myPointer = new int(10);

cout << "The value of myPointer is " << *myPointer << endl;

delete myPointer;

*myPointer = 5;

cout << "The value of myPointer is " << *myPointer << endl;

What is wrong with the above. You guessed right. myPointer is dangling. We've released the memory of the object whose address myPointer holds and then continued to use it. This problem is that although the program may run, this section of memory may be used by another dynamic object allocated after the delete. The values in that object will be corrupted by the continued use of myPointer. This is a very subtle programming bug and is very difficult to isolate. To avoid this bug, always set a pointer to 0, after the delete is called. Subsequent attempts to use the pointer will result in a run-time exception. This will immediately allow the bug to be identified and fixed. Here's the corrected code.

int *myPointer;

myPointer = new int(10);

cout << "The value of myPointer is " << *myPointer << endl;

delete myPointer;
myPointer = 0;

*myPointer = 5;    //This statement will cause an run-time exception, now.

cout << "The value of myPointer is " << *myPointer << endl;

Previous Page       Next Page