Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could accessing array element outside boundary corrupt it

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?

like image 467
Pasan W. Avatar asked Jun 12 '19 09:06

Pasan W.


People also ask

What happens if you go outside the bounds of an array?

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.

What happens if we access an array element outside of the range of the array?

Accessing array out of it's bounds is undefined behaviour, which means that anything can happen, even nothing.

What will happen if we try to access an array element that is beyond its declared dimension?

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.

What happens if we try to access element outside the array size in C++?

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.


1 Answers

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.

like image 143
lubgr Avatar answered Oct 06 '22 00:10

lubgr