Course contentsShow
← C
Lesson 1150 of 1,21916. Practice and ProjectsFree lesson

Range checking for array indices

Range checking for array indices

What you'll learn: How to prevent program crashes and security vulnerabilities by manually verifying that an index is within the valid boundaries of an array before accessing it.

The "Invisible Wall" Problem

In C, arrays are like a row of lockers. If you have 5 lockers, they are numbered 0 through 4. However, C is a "trusting" language—it won't stop you if you try to put a coat in locker number 10 or locker number -2.

If you try to access an index outside the range of your array, you fall into "Undefined Behavior." Your program might crash immediately (a Segfault), or worse, it might silently overwrite a different variable’s data. To write defensive code, you must build your own "invisible wall" to ensure you never step out of bounds.

Coding the Safety Gate

Defensive programming means assuming that any index provided by a user or a complex calculation is potentially wrong. You should always validate the index against the known size of the array using a simple if statement before you attempt to read or write to that memory location.

#include <stdio.h>

#define MAX_SAMPLES 5

int main() {
    int temperatures[MAX_SAMPLES] = {22, 25, 19, 24, 21};
    int userIndex;

    printf("Enter a sample index (0-4): ");
    scanf("%d", &userIndex);

    // Defensive Check: Validate the index before using it
    if (userIndex >= 0 && userIndex < MAX_SAMPLES) {
        printf("The temperature at index %d is %d\n", userIndex, temperatures[userIndex]);
    } else {
        printf("Error: Index %d is out of bounds! Access denied.\n", userIndex);
    }

    return 0;
}

Why This Matters

Without the if (userIndex >= 0 && userIndex < MAX_SAMPLES) check, a user could enter 100. The computer would then look at the memory address where the 100th element would be. This could lead to a "Buffer Over-read," where your program leaks secret information stored elsewhere in memory, or a "Buffer Overflow," where an attacker overwrites critical system instructions.

By checking the range first, you ensure your program handles errors gracefully rather than failing unpredictably.

Key takeaway

Always wrap array accesses in a boundary check to ensure the index is at least 0 and strictly less than the array's size.