• Home
  • 5.10 Out-of-Bounds Array Access

5.10 Out-of-Bounds Array Access

View Categories

5.10 Out-of-Bounds Array Access

Out-of-bounds array access occurs when an array is accessed using an index outside its valid range. C does not automatically check array bounds, so such access results in undefined behavior.

#include <stdio.h>

int main(void)
{
    int numbers[3] = {10, 20, 30};

    for (int i = 0; i < 3; i++)
    {
        printf("%d\n", numbers[i]);
    }

    return 0;
}

Example Output #

10
20
30

Explanation #

The array contains three elements, so its valid indices are 0, 1, and 2.

int numbers[3] = {10, 20, 30};

Accessing numbers[3] would exceed the valid range:

printf("%d\n", numbers[3]);  /* Undefined behavior */

The index 3 refers to a position immediately beyond the last element. C does not guarantee an error message, a crash, or any particular output.

Common Causes of Out-of-Bounds Access #

Cause Example
Using the array size as the last index numbers[3] for int numbers[3]
Starting a loop at the wrong index for (int i = 0; i <= 3; i++)
Using a negative index numbers[-1]
Calculating an incorrect index numbers[index + 1] when the result exceeds the bounds

Preventing Out-of-Bounds Access #

Use a loop condition that keeps the index below the element count:

size_t count = sizeof(numbers) / sizeof(numbers[0]);

for (size_t i = 0; i < count; i++)
{
    printf("%d\n", numbers[i]);
}

For functions that receive arrays as pointers, pass the element count separately and validate indices against that count. The sizeof calculation shown above works directly only when numbers is an actual array in that scope.

Out-of-bounds reads and writes can cause incorrect results, memory corruption, security vulnerabilities, or program crashes.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *