Short answer
std::vector with .at(), which throws std::out_of_range.Why C++ does not stop you
cppreference defines undefined behaviour in one line: there are "no restrictions on the behavior of the program." Its list of examples includes memory accesses outside array bounds.
The rule exists so that plain arrays stay fast and simple. An array is just a block of values, and table[i] goes straight to position i without a check. If i is too big, the program reads whatever sits at that spot. The compiler is allowed to assume you never do this.
For std::vector, the cppreference page for operator[] says no bounds checking is performed, and that a position at or beyond size() is undefined behaviour. (Since C++26 a hardened implementation may treat it as a contract violation instead. Do not count on that as a beginner.)
Three things that can happen
The same mistake can look different each time. Here is a program with the classic bug. The array has four values, so the valid positions are 0, 1, 2 and 3, but the loop uses <=:
#include <iostream>
int main() {
int table[4] = {10, 20, 30, 40};
int total = 0;
// Bug: i <= 4 also reads table[4], one past the end.
for (int i = 0; i <= 4; i++) {
total += table[i];
}
std::cout << total << '\n';
return 0;
}
The correct total is 100. On our test machine (g++ 16.2 on Windows) the program compiled with no warning under -Wall -Wextra and printed 1654651300, a leftover value mixed into the sum. Compiled again with -O2 -Wall, GCC warned that "iteration 4 invokes undefined behavior" and the program printed a different number, 868219572. Your output will differ again.
So the possible outcomes are:
- Garbage. The extra read picks up whatever was in memory, and the answer is wrong. This is what we saw.
- It seems fine. The extra value happens to be harmless, and the bug hides until you change something.
- A crash. If the index is far enough out, the read can touch memory the program does not own and the operating system stops it with a segmentation fault. See what a segmentation fault is for that side.
cppreference shows this same i <= 4 loop over int table[4] as an example of undefined behaviour, and notes that because the compiler may assume it never happens, it can produce surprising code. That is why you cannot test your way to confidence: a run that works proves nothing.
The off-by-one loop
Almost all beginner cases are the same bug. Array positions start at 0, so an array of size n has positions 0 to n - 1. The fix is < instead of <=:
#include <iostream>
int main() {
int table[4] = {10, 20, 30, 40};
int total = 0;
for (int i = 0; i < 4; i++) {
total += table[i];
}
std::cout << total << '\n';
return 0;
}
This prints 100.
Safer while learning - vector and at()
cppreference says std::vector::at checks the position and throws an exception of type std::out_of_range if it is outside the container. You can catch it and see exactly what went wrong:
#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
std::vector<int> scores {10, 20, 30};
for (std::size_t i = 0; i < scores.size(); i++) {
std::cout << "scores[" << i << "] = " << scores[i] << '\n';
}
try {
std::cout << scores.at(3) << '\n';
} catch (const std::out_of_range&) {
std::cout << "index 3 is out of range\n";
}
return 0;
}
This prints the three scores and then index 3 is out of range. Using scores.size() in the loop condition also means the loop adjusts if you add values later.
Plain array or [] | .at() | |
|---|---|---|
| Checks the index | No | Yes |
| Bad index gives | Undefined behaviour | std::out_of_range exception |
| Good for | Code you have proved correct | Learning and debugging |
Tools that catch it
The Clang documentation says AddressSanitizer detects out-of-bounds accesses to heap, stack and globals. You turn it on by compiling and linking with -fsanitize=address, and it reports the bad access when it happens. The documentation gives the typical slowdown as 2x, so it is for testing. We could not run it on our Windows test setup (the sanitizer build failed to link there), so we have not verified its output ourselves. Compiler warnings are a free first check too, as the -O2 -Wall warning above showed.
Quick checklist
- Valid positions run from 0 to size minus 1.
- Prefer
<over<=in loops over a size. - Use
.at()when an index comes from input or a calculation. - Do not trust a run that "works". Undefined behaviour can hide.
Get a feel for indexes
Counting from 0 feels wrong until you have done it many times. Reading short lines and predicting the result is good practice, and the beginner learning plan shows where arrays fit. If you are new to the main function wrapping these examples, start with what int main() means.
Teaches C++ to complete beginners as a game where you tap one real line of code at a time.
Get it on Google PlayFree to play. Halls 1 to 4 are free with no time limit, and free players can watch optional rewarded video ads for bonuses. Segfault Pro, a monthly subscription or a 3-month pass paid once, opens hall 5 and up, unlimited practice sets and mock exams, with no ads.
Segfault is a game that teaches C++ to complete beginners. You never type: each card shows a box and a target number, and you tap the one real line of C++ that makes them match. The 11 halls run from variables to if, loops, functions and arrays. Halls 1 to 4 are free; Pro opens hall 5 and up. It will not make you a programmer on its own, because you tap lines rather than write them.