< previous page page_984 next page >

Page 984
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
fined even though the pointer variables now have values (see Figure 17-7a).
*ptr2 = 44;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Stores the value 44 into the dynamic variable pointed to by ptr2 (see Figure 17-7b).
*ptr1 = *ptr2;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Copies the contents of the dynamic variable *ptr2 to the dynamic variable *ptr1 (see Figure 17-7 c).
ptr1 = ptr2;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Copies the contents of the pointer variable ptr2 to the pointer variable ptr1 (see Figure 17-7d).
delete ptr2;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
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.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Inaccessible Object A dynamic variable on the free store without any pointer pointing to it.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
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;

*ptr2 = 44;
*ptr1 = *ptr2;
delete ptr1;          // Avoid an inaccessible object
ptr1 = ptr2;
delete ptr2;
ptr1 = NULL;          // Avoid a dangling pointer
Figure 17-8 shows the results of executing this revised code segment.

 
< previous page page_984 next page >