Reputation: 1142
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
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