以前没注意这个问题,最近写一些代码时发现,在C/C++中,是不检查数组是否越界的。例如:
C language
#include <stdio.h>
int main()
{
int a[10];
a[3]=4;
a[11]=3;//does not give segmentation fault
a[25]=4;//does not give segmentation fault
a[20000]=3; //gives segmentation fault
return 0;
}
C++ language
#include <iostream>
using namespace std;
int main() {
int arr[1] = {0};
cout<<arr[2]<<endl;
return 0;
}
当然了,对于数组越界问题,不同编译器或许有不同的处理方案。根本原因在于,C/C++标准中仅是对界内访问做了明确的规定,而访问界外数据时却没有说怎么处理。正因如此,各大编译器处理方案也许不同。C/C++是不检查数组下标是否越界可以有效提高程序运行的效率,因为如果你检查,那么编译器必须在生成的目标代码中加入额外的代码用于程序运行时检测下标是否越界,这就会导致程序的运行速度下降。因此为了程序的运行效率,C/C++才不检查下标是否越界。
注意,其实“数组”这一概念,起于C语言,C++为了保持和C兼容,也没有做什么新的规定。
【In C++, bounds-checking is possible on class types. But an array is still the plain old C-compatible one. it is not a class. Further, C++ is also built on another rule which makes bounds-checking non-ideal. The C++ guiding principle is "you don't pay for what you don't use". If your code is correct, you don't need bounds-checking, and you shouldn't be forced to pay for the overhead of runtime bounds-checking.】