I have the following C++ example code and my thinking was that it throws a runtime error at LINE II.
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void printer(int i) {
cout << i << ", ";
}
int main() {
int mynumbers1[]={3, 9, 0, 2};
int mynumbers2[]={6, 1, 4, 5};
vector<int> v1(7);
sort(mynumbers2, mynumbers2 + 4);
sort(mynumbers1, mynumbers1 + 4);//LINE I
merge(mynumbers1, mynumbers1+5, mynumbers2, mynumbers2+5, v1.begin());//LINE II
for_each(v1.begin(), v1.end(), printer);
return 0;
}
However, the output of the program is actually:
0, 1, 2, 3, 4, 5, 6,
If I change, for example, the second parameter of merge to mynumbers1+6
then I get a runtime error:
*** Error in `./program': free(): invalid next size (fast): 0x0000000002468010 ***
0, 1, 2, 3, 4, 5, 6, Aborted (core dumped)
I am surprised because the past-the-end element is mynumbers1+4
and thus I expected mynumbers1+5
to throw a runtime error. But obviously this not the case.
I use g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
on an Ubuntu virtual machine.
Can someone explain to me why no runtime error is thrown?
Is it undefined behaviour?
Is it machine or implementation dependent?
And, most importantly, why in one "out of bounds" case a runtime error is thrown, but in the other "out of bounds" case no runtime error is thrown? Where does this error come from? The array or the vector?
Thank you for your time