< previous page page_1032 next page >

Page 1032
int* Func()
{
    int n;
      .
      .
      .
    return &n;
}
Remember that automatic variables are implicitly created at block entry and implicitly destroyed at block exit. The above function returns a pointer to the local variable n, but n disappears as soon as control exits the function. The caller of the function therefore receives a dangling pointer. Dangling pointers are hazardous for the same reason that uninitialized pointers are hazardous: when your program dereferences incorrect pointer values, it will access memory locations whose contents are unknown.
Testing and Debugging Hints
1. To declare two pointer variables in the same statement, you must use
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
int *p, *q;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
You cannot use
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
int* p, q;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Similarly, you must use
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
int &m, &n;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
to declare two reference variables in the same statement.
2. Do not confuse a pointer with the variable it points to.
3. Before dereferencing a pointer variable, be sure it has been assigned a meaningful value other than NULL.
4. Pointer variables must be of the same data type to be compared or assigned to one another.
5. In an expression, an array name without any index brackets is a pointer expression; its value is the base address of the array. The array name is considered a constant expression, so it cannot be assigned to. The following code shows correct and incorrect assignments.

 
< previous page page_1032 next page >