Course contentsShow
← C
Lesson 938 of 1,21913. Advanced CFree lesson

Accessing out-of-bounds memory

Accessing out-of-bounds memory

What you'll learn: Why C allows you to walk off the edge of an array and the unpredictable chaos that follows.

The Invisible Cliff

In many modern programming languages, the computer acts like a nervous parent. If you try to access the 11th element of a 10-item list, the language screams "Index Out of Bounds!" and stops the program immediately to keep you safe.

C is different. C treats you like a professional driver on a track with no guardrails. If you define an array of five integers, C sets aside exactly five slots of memory. If you try to access the sixth slot, C doesn't stop you. It simply calculates where that sixth slot would be in memory and tries to read or write whatever is sitting there.

The Neighbors You Didn't Invite

Think of memory like a long row of hotel rooms. You booked rooms 101 through 105. "Out-of-bounds" is like walking into room 106. You don't own it, but the door might be unlocked.

When you write to an index that doesn't exist, you are scribbling over data that belongs to something else. This is the essence of Undefined Behavior (UB).

#include <stdio.h>

int main() {
    int scores[3] = {90, 85, 80};
    
    // Valid indices are 0, 1, 2.
    // Index 3 is out-of-bounds!
    scores[3] = 999; 

    printf("Result: %d\n", scores[3]);
    return 0;
}

The Three Faces of Chaos

Because this is Undefined Behavior, one of three things usually happens:

  1. The Lucky Silent Failure: Your program writes to a piece of unused memory. Nothing seems to break today, but you've planted a "time bomb" that might crash the program later when that memory is actually needed.
  2. The Segmentation Fault: The operating system notices you are trying to touch memory you aren't allowed to access (like the "manager's office" in the hotel) and kills your program instantly to protect itself.
  3. Data Corruption: You accidentally overwrite another one of your own variables. Imagine changing a user's accountBalance just because you looped too far through a name string.

In C, the responsibility of staying within the lines belongs entirely to you.

Key takeaway

C does not check array boundaries; accessing out-of-bounds memory results in Undefined Behavior, which can silently corrupt data or cause sudden crashes.