Course contentsShow
← C
Lesson 563 of 1,2198. Memory ManagementFree lesson

Out-of-bounds array access on heap

Out-of-bounds array access on heap

What you'll learn: How to avoid the dangerous mistake of reading or writing data outside the memory boundaries you’ve allocated with malloc.

The "Reserved Seating" Problem

When you use malloc to create an array on the heap, the operating system gives you a specific block of memory. Think of it like reserving a row of five seats at a movie theater. You have the right to sit in seats 0, 1, 2, 3, and 4.

The problem is that C doesn’t hire a "security guard" to check your ticket every time you sit down. If you try to sit in "seat 5" (the sixth seat), C will let you do it. However, that seat wasn't part of your reservation. You might be sitting on someone else’s lap, or you might be sitting in a section that doesn't exist. This is an out-of-bounds access.

Why It’s Dangerous

On the heap, memory is a crowded neighborhood. When you write past the end of your allocated array, you are overwriting data that belongs to other variables or, worse, the internal bookkeeping information the program uses to track memory. This can lead to:

  1. Silent Corruption: Your program keeps running, but other variables suddenly change their values mysteriously.
  2. Crashes: The program hits a "Segmentation Fault" because you tried to touch memory that is strictly off-limits.
  3. Security Vulnerabilities: Hackers often use out-of-bounds writes to inject malicious code into a program’s memory.

The Code Example

Notice how we allocate space for 5 integers, but the loop tries to fill 10.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int size = 5;
    // Allocate space for 5 integers
    int *arr = malloc(size * sizeof(int));

    if (arr == NULL) return 1;

    // DANGER: The loop goes to 10, but the array only has 5 slots
    for (int i = 0; i < 10; i++) {
        // When i >= 5, we are accessing out-of-bounds heap memory
        arr[i] = i * 10; 
        printf("Writing to index %d\n", i);
    }

    free(arr);
    return 0;
}

In the example above, the program might crash the moment i reaches 5, or it might silently corrupt the heap and crash much later when you call free(). This "delayed crash" is what makes heap overflows so difficult to debug.

Key takeaway

Always verify your loop boundaries and pointer math; C will not stop you from writing past your malloc allocation, but doing so will corrupt your data or crash your program.