Course contentsShow
← C
Lesson 437 of 1,2196. Arrays and StringsFree lesson

Checking bounds before array access

Checking bounds before array access

What you'll learn: How to prevent program crashes and security vulnerabilities by manually verifying array indices before using them.

The "Invisible Fence" Problem

In many modern programming languages, the computer acts like a protective parent. If you try to grab the 10th item from a list that only has 5 items, the program stops immediately and tells you exactly what you did wrong.

C is different. C is like a high-speed sports car with no seatbelts. If you define an array of size 5 and ask for the item at index 10, C will often try to give it to you anyway. It looks at the memory address where the array starts, jumps ahead 10 spots, and reads whatever happens to be sitting there—whether it’s part of another variable, a piece of the operating system, or junk data. This is called Buffer Overflow, and it is the root cause of countless bugs and security hacks.

Be Your Own Guard

Because C won't stop you from crossing the boundary, you must build your own "fence." Before you ever access an array using a variable as an index, you must verify that the index is within the valid range: 0 to (Size - 1).

Imagine you are a librarian. Before you reach for a book on a shelf, you check the shelf number. If someone asks for shelf #50, but you only have 20 shelves, you don't walk into the wall—you stop and report an error.

Safety in Practice

Here is how you implement a manual bounds check:

#include <stdio.h>

int main() {
    int scores[5] = {88, 92, 79, 85, 90};
    int requestedIndex;

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

    // The Bounds Check: Always verify before accessing
    if (requestedIndex >= 0 && requestedIndex < 5) {
        printf("The score is: %d\n", scores[requestedIndex]);
    } else {
        printf("Error: Index %d is out of bounds!\n", requestedIndex);
    }

    return 0;
}

In this example, the if statement acts as a gatekeeper. By checking that requestedIndex is at least 0 and strictly less than the array size, we ensure the program never touches memory it doesn't own.

Why This Matters

Accessing out-of-bounds memory is "Undefined Behavior." Sometimes your program will crash (Segmentation Fault), which is actually lucky because you know there is a bug. Other times, it will quietly work but produce wrong results, making the bug nearly impossible to find later. Always validate your indices first.

Key takeaway

C does not check array boundaries for you; you must use if statements to verify that an index is valid before accessing array data.