|
|
|
|
|
|
|
The second common error is to dereference the null pointer or an uninitialized pointer. On many systems, an attempt to dereference the null pointer produces a run-time error message such as NULL POINTER DEREFERENCE, followed immediately by termination of the program. When this event occurs, you have at least some notion of what went wrong with the program. The situation is worse, though, if your program dereferences an uninitialized pointer. In the code fragment |
|
|
|
|
|
|
|
|
int num;
int* intPtr;
num = *intPtr; |
|
|
|
|
|
|
|
|
the variable intPtr has not been assigned any value before we dereference it. Initially, it contains some meaningless value such as 315987, but the computer does not know that it is meaningless. The machine simply accesses memory location 315987 and copies whatever it finds there into num. There is no way to test whether a pointer variable contains an undefined value. The only advice we can give is to check the code carefully to make sure that every pointer variable is assigned a value before being dereferenced. |
|
|
|
|
|
|
|
|
The third errorleaving inaccessible objects on the free storeusually results from either a shallow copy operation or incorrect use of the new operator. In Figure 17-11, we showed how the built-in assignment operator causes a shallow copy; the dynamic data object originally pointed to by one pointer variable remains allocated but inaccessible. Misuse of the new operator also can leave dynamic data inaccessible. Execution of the code fragment |
|
|
|
|
|
|
|
|
float* floatPtr;
floatPtr = new float;
*floatPtr = 38.5;
floatPtr = new float; |
|
|
|
|
|
|
|
|
creates an inaccessible object: the dynamic variable containing 38.5. The problem is that we assigned a new value to floatPtr in the last statement without first deallocating the variable it pointed to. To guard against this kind of error, examine every use of the new operator in your code. If the associated variable currently points to data, delete the pointed-to data before executing the new operation. |
|
|
|
|
|
|
|
|
Finally, dangling pointers are a source of bugs and can be difficult to detect. One cause of dangling pointers is deallocating a dynamic data object that is pointed to by more than one pointer. Figures 17-7d and 17-7e pictured this situation. A second cause of dangling pointers is returning a pointer to an automatic variable from a function. The following function, which returns a function value of type int*, is erroneous. |
|
|
|
|
|