为什么在C++中访问过去时结束元素时没有运行时错误

Why is there not runtime error when accessing past the past-the-end element in C++?

本文关键字:元素 运行时错误 结束 过去时 C++ 访问 为什么      更新时间:2023-10-16

我有下面的C++示例代码,我的想法是它在LINEII上引发了一个运行时错误。

#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;
}

然而,程序的输出实际上是:

0, 1, 2, 3, 4, 5, 6, 

例如,如果我将merge的第二个参数更改为mynumbers1+6,那么我会得到一个运行时错误:

*** Error in `./program': free(): invalid next size (fast): 0x0000000002468010 ***
0, 1, 2, 3, 4, 5, 6, Aborted (core dumped)

我很惊讶,因为过去的结束元素是mynumbers1+4,因此我预计mynumbers1+5会抛出运行时错误。但显然情况并非如此。

我在Ubuntu虚拟机上使用g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4

有人能向我解释为什么没有抛出运行时错误吗
这是未定义的行为吗
它依赖于机器还是实现
而且,最重要的是,为什么在一种"越界"情况下会抛出运行时错误,而在另一种"界外"情况下却没有抛出任何运行时错误?这个错误是从哪里来的?数组还是矢量?感谢您抽出时间

C/C++不执行任何范围检查。这是因为存在性能惩罚。因此,访问超出其范围的数组是未定义的行为。任何事情都可能发生,包括数据泄露。你觉得自己很幸运,程序崩溃了。