How to avoid array overflow in C ++?

1

My program was showing strange behavior, until I discovered that there was an overflow of array , for example:

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

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

However, C ++ does not say anything and the program literally detonates memory, generating unpredictable behavior in the program.

How can I make C ++ warn (and avoid) when this happens?

    
asked by anonymous 12.05.2018 / 15:26

2 answers

4

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 array , or vector , or something similar. And use an iterator that ensures you can not go beyond the limits ( example , other , one more , < a href="https://en.stackoverflow.com/a/293230/101"> with string , a simplified , example with and without iterator but still secure , a last ).

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

If you want more guarantees, switch languages. C ++ is powerful, flexible and performative, but not the safest that exists. It requires the programmer to know what they are doing.

    
12.05.2018 / 15:59
2

Complementing the Maniero solution.

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

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

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

    
14.05.2018 / 17:03