|
|
 |
|
|
|
|
int arrA[5] = {10, 20, 30, 40, 50};
int arrB[5] = {60, 70, 80, 90, 100};
int* ptr;
ptr = arrB; // OK--you can assign to a variable
arrA = arrB; // Wrong--you cannot assign to a constant |
|
|
|
|
|
|
|
|
6. If ptr points to a struct, union, or class variable that has an int member named age, the expression |
|
|
|
 |
|
|
|
|
*ptr.age |
|
|
|
 |
|
|
|
|
is incorrect. You must either enclose the dereference operation in parentheses |
|
|
|
 |
|
|
|
|
(*ptr).age |
|
|
|
 |
|
|
|
|
or use the arrow operator: |
|
|
|
 |
|
|
|
|
ptr->age |
|
|
|
|
|
|
|
|
7. The delete operator must be applied to a pointer whose value was previously returned by new. Also, the delete operation leaves the value of the pointer variable undefined; do not use the variable again until you have assigned it a new value. |
|
|
|
|
|
|
|
|
8. A function must not return a pointer to automatic local data, or else a dangling pointer will result. |
|
|
|
|
|
|
|
|
9. If ptrA and ptrB point to the same dynamic data object, the statement |
|
|
|
 |
|
|
|
|
delete ptrA; |
|
|
|
 |
|
|
|
|
makes ptrB a dangling pointer. You should now assign ptrB the value NULL rather than leave it dangling. |
|
|
|
|
|
|
|
|
10. Deallocate dynamic data when it is no longer needed. Memory leaks can cause you to run out of memory space. |
|
|
|
|
|
|
|
|
11. Inaccessible objectsanother cause of memory leaksare caused by |
|
|
|
 |
|
|
|
|
a. shallow copying of pointers that point to dynamic data. When designing C++ classes whose objects point to dynamic data, be sure to provide a deep copy operation and a copy-constructor. |
|
|
|
 |
|
|
|
|
b. using the new operation when the associated variable already points to dynamic data. Before executing new, use delete to deallocate the data that is currently pointed to. |
|
|
|
|
|