When accessing memory that you should not access, it can go two ways, depending on whether your program owns that part of memory or not:
- That part of memory does not belong to your process: The OS will notice this misbehavior and terminate your program. (The famous segmentation fault)
- That part of memory does belong to your process: In that case, you will silently read or overwrite your own data!
Which of these happens may very well be completely random. It depends on the compiler and can also vary with each run, making it a real pain to debug!
The big issue for you as a programmer is the second scenario. The issue can easily go unnoticed but the effects are horrible. The address you are accessing will likely contain data that is part of another variable.
Now if this is just a character or a number, you will probably notice the unusual, seemingly random character/number at the end of your string/vector - but now imagine a vector of objects, e.g. vector<SomeClass> foo
You might never bother to look directly at the contents of foo
because it doesn't contain nicely human readable information.
The solution, as vivi already hinted at, is to access elements via .at()
, because it will always generate an exception when you try to read/write outside the bounds of your array, so your mistake does not go unnoticed and you can fix it right away.