How to avoid array overflow in C++?

My program was exhibiting some weird behavior, until I found out that there was a burst of array , for example:

int arr[3];
for (int i = 0; i<10; i++) {
    arr[i]=i;
    cout << arr[i];
}

In this clear example, i exceeds the limit of only 3 elements of the array.

However C++ does not warn anything and the program will literally detonate the memory, generating unpredictable behavior in the program.

How Can you make C++ warn (and avoid) when it occurs this?

Author: lazyFox, 2018-05-12

2 answers

Programming in C++ instead of programming in C. What you are doing is C and not C++. It works because C++ tries to maintain compatibility with C, but it is not the most suitable.

Use a array, or one vector, or something like that. And use an iterator that ensures you won't be able to go beyond the bounds (example, other, one more, com string, a simplified, example with and without iterator but still safe, one last ).

There are external tools that can parse and try report you have an error.

If you want more guarantees, change language. C++ is powerful, flexible, and performant, but not the safest there is. It requires the programmer to know what he is doing.

 4
Author: Maniero, 2018-05-12 13:59:52

Complementing the Maniero solution.

This is a problem of dynamic semantics, in which it is only possible to know if it will generate a critical error during execution, so it does not become a responsibility of the compiler, since this failure does not prevent the compilation or the execution of the program.

This is not an error but a unreliable access to a piece of memory not allocated by the variable .

In this article you can view that it is possible to access an area of memory outside the limits of the array, but it is not possible to write to it.

 2
Author: Sveen, 2018-05-14 16:06:43