C/C++ 不检查数组下标是否越界

以前没注意这个问题,最近写一些代码时发现,在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.】

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值