A girl and a robot thinking together

Think together · Start with a story

Five storage slots are labeled 0 through 4, but the robot tries to open slot 5. There is no such position in the picture.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Check the length5
  2. Valid range0 through 4
  3. Check before accessIndex must be less than 5

An array out-of-bounds error means accessing a position outside the valid range.

An ordinary C++ array does not automatically add another slot for you, and it does not guarantee that every out-of-bounds access will report an error immediately. It may look fine while already being unreliable.

01What does out of bounds mean?

If an array has five elements, its valid indexes are 0, 1, 2, 3, and 4. Accessing an index outside that range is out of bounds.

02What happens after going out of bounds?

The most dangerous part is that the result is not predictable.

Seems normal

No obvious problem appears right away.

Strange value

Data outside the array may be read.

Data damage

Nearby memory may be overwritten.

Program crash

An access error may occur.

03Why does C++ not always report an error automatically?

Accessing an ordinary array with an index usually does not automatically check bounds at runtime.

This gives C++ a lot of control and performance, but it also means the programmer must ensure indexes are valid.

04Where do loops most often go wrong?

for (int i = 0; i <= 5; i++) {
    std::cout << a[i];
}

When i == 5, the loop accesses a[5].

The correct range is:

for (int i = 0; i < 5; i++)

05Are there tools that check bounds?

std::array and std::vector provide .at():

v.at(i)

If the index is out of range, an exception reports an error instead of silently performing an undefined access.

Ordinary [] access usually still does not perform this check.

06How can you reduce out-of-bounds errors?

Remember the range

Length n → 0 through n-1.

Manage the length consistently

Do not write magic numbers everywhere.

Trace it in a table

Check where the loop variable ends up.

What you have learned

  • An array out-of-bounds error means accessing an element outside the valid range.
  • Going out of bounds on an ordinary C++ array is undefined behavior.
  • No crash does not mean the code is correct.
  • A common mistake is writing i <= n instead of i < n.
  • at() on a container provides bounds checking.

Next: Two-Dimensional Arrays: Arrange Data in a Grid

Your turn to try

If a loop uses the condition i <= 5 to access a five-element array, which value is invalid?

Ready? Open to see the explanation

The access where i is 5 is invalid when counting from 0. The condition must keep i < 5; also avoid negative indexes.