Course contentsShow
← C
Lesson 478 of 1,2197. PointersFree lesson

Bounds checking and pointer safety

Bounds checking and pointer safety

What you'll learn: Why C allows you to access memory outside of an array and how to prevent these dangerous "out-of-bounds" errors.

The Invisible Guardrail

In many modern programming languages, the computer acts like a nervous parent. If you try to grab the 11th item from a 10-item list, the program screams "Error!" and stops immediately. This is called bounds checking.

C is different. C is like a high-speed sports car without seatbelts. Because C prioritizes speed and direct hardware control, the compiler assumes you know exactly what you are doing. If you have an array of 5 integers and you ask for the 500th one, C will simply calculate that memory address and try to read it anyway.

Memory Neighbors

Think of an array like a row of five houses on a street. You own houses #0 through #4. If you try to walk into house #5, you aren't walking into your own property—you are breaking into your neighbor’s house.

When you access an index outside your array's bounds:

  1. Garbage Data: You might read a value that makes no sense.
  2. Crashes: You might hit a "Segmention Fault" because you tried to touch memory the operating system has reserved for itself.
  3. Silent Corruption: You might accidentally overwrite a variable used elsewhere in your program, causing a bug that only appears hours later.

Staying Safe

Since C won't stop you from crossing the line, you must be your own guardrail. The most common way to do this is by strictly comparing your pointer or index against the known size of the array.

#include <stdio.h>

int main() {
    int scores[3] = {92, 85, 70};
    int size = 3;

    // Dangerous: Accessing index 5 is "Out of Bounds"
    // printf("%d", scores[5]); // This is a security risk!

    // Safe: Always check the index against the size
    for (int i = 0; i < size; i++) {
        printf("Score %d: %d\n", i, scores[i]);
    }

    return 0;
}

In the code above, the loop condition i < size acts as the manual safety catch. Without it, the pointer used behind the scenes by the array would keep marching forward into unknown territory.

Key takeaway

C does not perform automatic bounds checking; you must manually ensure your pointers and indices never exceed the array's size to avoid crashes and security vulnerabilities.