argamanza
argamanza

Reputation: 1142

Right type of exception for access of array index which doesn't exist in memory?

I'm new to C++ exceptions, and i can't find the right type of exception for a bad memory access attempt.

Let's assume i allocated memory for 10 integers with this code:

int* intArray = new int[10];

for(int i = 0;i < 10;i++){
    intArray[i] = i+1;
}

And while trying to read it i made some logical mistake which will cause the program to access a memory i didn't allocate, for example:

for(int i = 0;i < 15;i++){
    cout << intArray[i] << endl;
}

What is the right type of exception to catch?

Thanks!

Upvotes: 0

Views: 62

Answers (1)

kvorobiev
kvorobiev

Reputation: 5070

This code

int* intArray = new int[10];
...    
for(int i = 0;i < 15;i++){
    cout << intArray[i] << endl;
}

does not throw an exception. This will lead to undefined behavior. Most likely, you just get the output of random data. When you create an array with new operator you get a sequence of elements with contiguous addresses. C++ does not have mechanisms to check the length of such arrays in runtime.

Upvotes: 2

Related Questions