c++ – Access outside the size of the array

Question:

I am studying the basic features of C ++ and here is the following code:

int mas[12];

mas[15]=15;
cout<<"15 element = "<<mas[15]<<"\n";

for reasons I do not understand, it works. After all, this is an overflow of the array?

Answer:

C ++ is an unsafe language.

The rules of the language say that you cannot go beyond the bounds of the allocated memory. The responsibility for following the rules rests with you, the programmer. C ++, unlike safe languages, doesn't check if you're following the rules, so you don't get an error directly at that point.

But once you've broken the rules, any trouble can happen. The standard emphasizes that if you violate the rules, all guarantees of the language are canceled.

When reading out of bounds of an array, if you are lucky, and memory at an offset of 15 element sizes from the beginning of the array is available, and does not contain anything bad (on Intel's architecture, there is no "bad", but on others it is completely ) and if the optimizer is not very smart, you just read some incomprehensible meaning.

In case you are less fortunate, the program will simply crash.

And in a very bad case, the program will begin to behave strangely, and in some distant place that is not connected with this point.

When writing, everything is even worse, some important data structure may accidentally appear at this address (for example, it may be the return address from the current function), and you will overwrite it with some incomprehensible value on the principle “to whom will God send”.

Just don't do that, C ++ trusts you.

Scroll to Top