Manipulating array out of bounds, can't seem to understand implications


1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
   int array[5] = {0};
   array[6] = 100;
   std::cout << array[6];
}


How does this work? Aren't we supposed to not go out of bounds for arrays?
Even if i went out of bounds here things work perfectly fine. What does array "bound" actually mean and what's its use ?
Yes, you are supposed to not go out of bounds. The behavior of your program is undefined if you do. Undefined behavior could be anything: crash now, crash later, nothing special, some unrelated variable changing, etc. Unrefined behaviour also often changes between debug and release, when compiler version or platform changes, or when some more code is added. In short, this program has an error, don't do that.
Last edited on
You have a home. Your neighbour has a home. If they come and poo on your kitchen, they store something "out of bounds". Your kitchen is not theirs to use, is it? For a while such behaviour might seem to them to "work perfectly fine", but I bet that eventually things will turn messy. It does depend on how often you need your kitchen.

Certain compilers with certain options (e.g. MSVC debug build) inject additional code that shout out "not within allowed range". (MSVC release has no such checks in order to be more efficient, and with it the crashes are thus harder to debug.)
Topic archived. No new replies allowed.