Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of (STL) copy with undefined behaviour?

Tags:

c++

stl

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;
}
like image 244
Ely Avatar asked Mar 05 '23 06:03

Ely


1 Answers

Yes, it's UB.

The first thing std::copy will do is dereference v1.end(), and doing so causes undefined behavior.

like image 183
HolyBlackCat Avatar answered Mar 18 '23 23:03

HolyBlackCat