Book
Collection
Click for Table of Contents
© 2025 by Rance D. Necaise
C Primer for Python Programmers
Copyright © 2025
Rance D. Necaise

7.5 Range Checking

In your experience with Python, you may remember that an exception is raised if you attempt to access a list element that is out of range. In C, no range checking is performed when accessing an array. For example, given the array declaration from an earlier section

  1. int values[5];

if you attempt to access an element outside the range 0..5,

  1. values[12] = 25;

the results are unpredictable. In C, memory is allocated in blocks called pages or segments. As more memory is needed, the system allocates more pages to your program. When you access an element that is out of range, C simply calculates the address of the element as if the array is of infinite size. Thus, in this example, memory immediately after the values array will be accessed. If that falls on a page of memory that has been allocated to your program, the statement is executed, with unknown results. Otherwise, the program will abort with a "Segmentation Fault".

Warning
Warning

Setting an element of an array that is out of range overwrites memory at the given location. This could result in modifying the contents of another variable or array, or even changing an executable statement. In both cases, the results are unpredictable.

Question 7.5.1

Consider the code segment below and for each of the following questions, indicate whether the element access is in range or out of range.

  1. const int MAX_SIZE = 50;
  2. const int NUM_VALUES = 12;
  3.  
  4. float averages[MAX_SIZE];
  5. int values[NUM_VALUES];
  6. char grades[] = ['A', 'B', 'C', 'D', 'F'];
  7. int i = 4;
  8. int x;
Select the correct answer by clicking on the appropriate button.
  1. in range|out of range
  2. x = averages[49];
  3. values[12] = 0;

    The values array has exactly 12 elements, with the indices 0..11. Thus, attempting to access element 12 will be out of range.

  4. grades[0] = 'a';
  5. x = values[2] + values[i];
  6. averages[MAX_SIZE] = values[i];

    The averages array has exactly 50 elements. Attempting to access element 50, will be out of range.

  7. printf("%c", grades[i+2])
    Since i has a value of 4, i+2 will be six which is out of the valid range of indices (0..4) for the grades array.