22F. Array Bounds

If your program uses a nonexistent index in an array, the error will not be detected automatically. It cannot possibly be detected automatically because an array is a pointer; it says where the chunk begins, but does not provide any information about where the chunk ends. The program computes the memory address that you refer to (using pointer arithmetic) and uses that memory as if it is part of the array's chunk. That is a dangling pointer error, and can cause your program to devolve into chaos.

Make sure that you are alert. If you are not absolutely sure that a given index is correct, do your own array bounds check. For example, if A's chunk has size n, then code

  if(i < 0 || i >= n)
  {
    printf("funname: bad array index %d\n", i);
    exit(1);
  }
checks that index i is acceptable for A and aborts the program if not. (The function containing this code is assumed to be funname.)

The standards for this course require your program not to make array-bounds errors.


Exercises

  1. What happens if you use an index that is not an allowed index for an array? Answer