PrevPrev UpUp NextNext


Harmless pointers

Are all pointers evil? Well, they make your software more flexible and dynamic. Moreover, they are necessary in C to implement reference parameters.

Parameters are always passed by value in C. If you want to return multiple values by a function, you need reference parameters. C programmers use an idiom for reference parameters by using pointers:

  // a and b are reference parameters
  void f (int *a, int *b) {
    *a = 1; *b = 2; // return values
  }

  ...f (&x, &y)... // pass by reference

The pointers used in this idiom to simulate reference parameters are harmless in the sense that their life time is definitely not longer than the object they are pointing to. So, they are not dangling references.

In contrast, the following code creates a dangling reference:

  int *p;

  void f (int *a) {
    p = a; 
  }

  void g() {
   int x;
   f (&x);
  }

  int main () {
   g ();
   ...*p... // ouch, a dangling reference
  }

Bauhaus identifies all pointers used for reference parameters.

Last modified: Wed Aug 27 12:19:58 MET DST 2003