In an assessment I chose the option runtime error on LINE I. There was no such option as Undefined Behaviour although I thought that would be the correct option to choose.
I am not sure but I'd reckon there is a mistake in the assessment. I compiled and ran the program and it prints indeed 3, 9, 0, 2, 1, 4, 5,
with three different compilers (Cpp.sh, here and locally on Mac OS X).
Does the program have Undefined Behaviour due to LINE I?
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void printer(int i) {
cout << i << ", ";
}
int main() {
int mynumbers[] = { 3, 9, 0, 2, 1, 4, 5 };
vector<int> v1(mynumbers, mynumbers + 7);
copy(mynumbers, mynumbers + 7, v1.end());//LINE I
for_each(v1.begin(), v1.end(), printer);//LINE II
return 0;
}
Yes, it's UB.
The first thing std::copy
will do is dereference v1.end()
, and doing so causes undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With