为什么在C++中访问过去时结束元素时没有运行时错误
Why is there not runtime error when accessing past the past-the-end element in C++?
我有下面的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++不执行任何范围检查。这是因为存在性能惩罚。因此,访问超出其范围的数组是未定义的行为。任何事情都可能发生,包括数据泄露。你觉得自己很幸运,程序崩溃了。
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 运行时错误:矢量下标超出范围:正在检查空集
- Leetcode 540 上的运行时错误.排序数组中的单个元素
- 动态分配数组中的运行时错误,用于删除 C++ 中的元素
- 在运行时C++将元素插入到向量中.引发运行时错误
- 访问矢量容器的元素时发生运行时错误
- Linux中的c++运行时错误::glibc检测到free():无效的下一个大小(快速):堆栈具有void ptr元素
- 为什么在C++中访问过去时结束元素时没有运行时错误
- 为什么当我访问数组的越界元素时没有收到运行时错误?