next up previous
Next: Improvements: Vector addition Up: Simple Classes: myvector.h Previous: Improvements: Code placement

Improvements: Range checking

Suppose we define a vector of length five but try to access the tenth element of the vector. The compiler will let us do that, but we are then going out of bounds. We may end up accessing some other numbers in our program, or parts of our machine code, or we might even be attempting to access memory that belongs to someone else. The first two events cause bugs that are extremely difficult to find. The last event causes a runtime error variously called ``Segmentation fault'' or ``bus error'' that stops execution of the code. In all cases this should not be allowed to happen. We can prevent it by including a procedure for checking all subscripts to be sure they are inside the legal range, i.e. $[0,1,\ldots{},n-1]$ for a vector of size $n$. We do this by modifying the subscript method as follows:

class vector {
 private:
  int size;
  double *vec;    // Note that only a pointer is kept here
  // Auxiliary function for internal range checking
  int range(int i);

 public:
  ...
  // Accessors
  double & operator[](int i){ return vec[range(i)]; }
  ...
};

// Auxiliary function for range checking
inline int vector::range(int i)
{
  if(i < 0 || i >= size)
    {
      cerr << "FATAL vector::range(" << i << ") out of bounds [0," 
	   << size-1 <<"]\n";
      exit(1);
    }
  return i;
}

Here we have defined a private method range that checks the subscript. When we write a[i] the new subscript method is called and here is what happens. The integer argument i is first handed to the range function. That function checks to be sure that i is in the legal range. If not, it quits. If so, the range function returns the value i unchanged to the operator[] method where it is then used to extract vec[i].

Notice that the code for the range method appears outside the class declaration, so its name has the prefix identifying it as a member of the vector class and it is made inline.


next up previous
Next: Improvements: Vector addition Up: Simple Classes: myvector.h Previous: Improvements: Code placement
Carleton DeTar 2007-08-17