How to avoid array overflow in C++?

Asked

Viewed 263 times

1

My show was exhibiting some weird behavior, until I found out that there was a bang 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 array.

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

How C++ can be made to warn (and avoid) when this occurs?

  • Just like @Maniero said, it’s best to use a built in iterator or compare to the array size.

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 is not the most suitable.

Use a array, or a vector, or something like that. And use an iterator that ensures you can’t go beyond the limits (example, another, one more, with string, a simplified, example with and without iterator but still secure, one last).

There are external tools that can analyze and try to inform that you have an error.

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

2

Complementing the Maniero solution.

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

It’s not a mistake, it’s a mistake unreliable access to a piece of memory not allocated by the variable.

In this article it is possible to visualize that it is possible to access a memory area outside the limits of the array, but it is not possible to write to it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.