|
|
|
|
|
|
|
When you call delete on a pointer, the memory it points to is freed. Calling delete on that pointer again will crash your program! When you delete a pointer, set it to 0 (null). Calling delete on a null pointer is guaranteed to be safe. For example: |
|
|
|
|  |
|
|
|
|
Animal *pDog = new Animal;
delete pDog; //frees the memory
pDog = 0; //sets pointer to null
//
delete pDog; //harmless |
|
|
|
|
|
|
|
|
|
LISTING 9.4 ALLOCATING AND DELETING A POINTER |
|
|
|
 |
|
|
|
|
1: // Listing 9.4
2: // Allocating and deleting a pointer
3:
4: #include <iostream.h>
5: int main()
6: {
7: int localVariable = 5;
8: int * pLocal= &localVariable;
9: int * pHeap = new int;
10: *pHeap = 7;
11: cout << localVariable: << localVariable << \n;
12: cout << *pLocal: << *pLocal << \n;
13: cout << *pHeap: << *pHeap << \n;
14: delete pHeap;
15: pHeap = new int;
16: *pHeap = 9;
17: cout << *pHeap: << *pHeap << \n;
18: delete pHeap;
19: return 0;
20: } |
|
|
|
|
|
|
|
|
localVariable: 5
*pLocal: 5
*pHeap: 7
*pHeap: 9 |
|
|
|
|
|
|
|
|
Analysis: Line 7 declares and initializes a local variable. Line 8 declares and initializes a pointer with the address of the local variable. Line 9 declares another pointer but initializes it with the result obtained from calling new int. This allocates space on the free store for an int. Line 10 assigns the value 7 to the newly allocated memory. Line 16 prints the value of the local variable, and line 12 prints the value pointed to by pLocal. As expected, these are the same. Line 13 prints the value pointed to by pHeap. It shows that the value assigned in line 10 is, in fact, accessible. |
|
|
|
|
|