fined even though the pointer variables now have values (see Figure 17-7a).
*ptr2 = 44;
Stores the value 44 into the dynamic variable pointed to by ptr2 (see Figure 17-7b).
*ptr1 = *ptr2;
Copies the contents of the dynamic variable *ptr2 to the dynamic variable *ptr1 (see Figure 17-7 c).
ptr1 = ptr2;
Copies the contents of the pointer variable ptr2 to the pointer variable ptr1 (see Figure 17-7d).
delete ptr2;
Returns the dynamic variable *ptr2 back to the free store to be used again. The value of ptr2 is undefined (see Figure 17-7e).
In Figure 17-7d, notice that the variable pointed to by ptr1 before the assignment statement is still there. It cannot be accessed, however, because no pointer is pointing to it. This isolated variable is called an inaccessible object. Leaving inaccessible objects on the free store should be considered a logic error and is a cause of memory leaks.
Notice also that in Figure 17-7e ptr1 is now pointing to a variable that, in principle, no longer exists. We call ptr1 a dangling pointer. If the program later dereferences ptr1, the result is unpredictable. The pointed-to value might still be the original one (44), or it might be a different value stored there as a result of reusing that space on the free store.
Inaccessible Object A dynamic variable on the free store without any pointer pointing to it.
Dangling Pointer A pointer that points to a variable that has been deallocated.
Both situations shown in Figure 17-7ean inaccessible object and a dangling pointercan be avoided by deallocating *ptr1 before assigning ptr2 to ptr1, and by setting ptr1 to NULL after deallocating *ptr2.
#include <stddef.h> // For NULL
.
.
.
int* ptr1 = new int;
int* ptr2 = new int;