2

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

Ely
  • 10,860
  • 4
  • 43
  • 64
  • 1
    there are so many duplicates of this – phuclv Aug 04 '16 at 06:36
  • look at `std::array` to help with bounds checking. – Paul Rooney Aug 04 '16 at 06:56
  • Thank you guys. But both comments do not help me to be honest. I showed two cases that are "out of bound". In one case there is a run time error and in the other, surprisingly, there is no run time error. Don't you find that confusing and inconsistent? I don't think it is a duplicate. Apart, I refer to C++ and not to C (which has its own specification); note that I use Vector in the example. – Ely Aug 04 '16 at 17:04
  • 1
    @Elyasin as it stated in many answers compiler does not have to check for UB and it is not obligated to generate any code to make your program fail in UB. So you have UB in both cases, in one it may crash in another it may not. Nobody would guarantee that UB has consistent behavior. – Slava Aug 04 '16 at 17:15

1 Answers1

5

C/C++ does not perform any range checking. This is because there is a performance penalty. So accessing an array beyond its range is undefined behaviour. Anything can happen including data corruprion. Consider yourself lucky, the program crashed.

doron
  • 27,972
  • 12
  • 65
  • 103