Is it possible that accessing an array outside its boundary corrupt its existing elements
MyObject* array[10];
for(int i=0; i<10; i++)
{
array[i] = nullptr;
}
array[1] = new MyObject();
array[8] = new MyObject();
array[15] = new MyObject();
could accessing array[15] result in the corruption of the elements between 0-10?
If you read or write outside of an array's bounds, you may read or write garbage or (if you are lucky) you may get a segmentation fault which at least tells you there's a problem. In the end, it is up to you to make sure that your program respects the bounds of its arrays.
Accessing array out of it's bounds is undefined behaviour, which means that anything can happen, even nothing.
Accessing array elements greater than its size If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception.
It is left undefined what happens if you go out of bounds. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program.
could accessing
array[15]
result in the corruption of the elements between 0-10?
Yes. This is undefined behavior, and the nature of UB is that anything can happen. In particular, it usually doesn't make much sense to reason about what could happen or what is more likely to happen. It can be anything, including the corruption of some array elements that were intact before UB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With