Your program has undefined behaviour the moment it tries to evaluate start - 13
.
start
points to the first element of the a
array, so start - 13
creates an invalid pointer, because it's out of the array's bounds. You simply cannot do that, and it doesn't make sense either. What do you expect the pointer to point at, exactly?
Mind that this is undefined behaviour even if you do not dereference the pointer.
In any case, undefined behaviour means your program can do anything, and "anything" includes throwing random exceptions.
And in fact, I cannot reproduce the std::bad_alloc
exception. For example, the latest Clang throws std::length_error
instead, and the latest Visual C++ just crashes. It also depends on the compiler flags.
What probably happens in your case is that the compiler has produced binary code which simply goes on with the invalid pointer and passes it to the vector constructor, which then tries to create a huge integer range from it, which fails.
Perhaps you intended something like this instead?
void test_bad_alloc(unsigned char *start, unsigned char* end) {
try {
vector<int> v = vector<int>(start + 1, end - 13);
}catch (bad_alloc) {
std::cout<<"bad alloc"<<std::endl;
}
}
// ...
test_bad_alloc(a, a + 20);
I also couldn't help but notice a Java-ism in the vector definition line. You can, and should, write it like this instead:
vector<int> v(start + 1, end - 13);